diff --git a/cloud/apps/relay-edge/src/host-relay-handshake.ts b/cloud/apps/relay-edge/src/host-relay-handshake.ts index bc153be8a0c..22614a1fe85 100644 --- a/cloud/apps/relay-edge/src/host-relay-handshake.ts +++ b/cloud/apps/relay-edge/src/host-relay-handshake.ts @@ -191,7 +191,7 @@ export abstract class HostRelayHandshake extends HostRelayBase { }) // After the ack, which strict shipped parsers must see unchanged; only hosts that asked get it. if (a.clientKeepalive) { this.send(ws, { type: 'keepalive-offer', v: 1, intervalMs: this.config.pingIntervalMs }) } - metric(this.env, 'control_active', 1, rebind ? 'rebind' : 'new', [], '', a.place) + metric(this.env, 'control_active', 1, rebind ? 'rebind' : 'new', [], a.clientKeepalive ? 'keepalive' : 'legacy', a.place) await this.reschedule() } } diff --git a/cloud/apps/relay-edge/src/host-relay.ts b/cloud/apps/relay-edge/src/host-relay.ts index 958232f8ff4..14f5a0f544f 100644 --- a/cloud/apps/relay-edge/src/host-relay.ts +++ b/cloud/apps/relay-edge/src/host-relay.ts @@ -187,7 +187,8 @@ export class HostRelay extends HostRelayPhones { // Same order as the cells' heartbeat: expired auth past its grace, then the 6 h lease. if (now > a.claims.exp + CONTROL_CONTINUITY_LIMITS.expiredAuthExistingSpliceGraceMs) { const sinceRefreshS = a.lastRefreshAt === undefined ? -1 : Math.round((now - a.lastRefreshAt) / 1000) - metric(this.env, 'auth_expired_close', sinceRefreshS, a.lastRefreshAt === undefined ? 'never' : 'refreshed', [], '', a.place) + const seenAgoS = Math.round((now - seen) / 1000) + metric(this.env, 'auth_expired_close', sinceRefreshS, a.lastRefreshAt === undefined ? 'never' : 'refreshed', [seenAgoS], this.keepalive(a) ? 'keepalive' : 'legacy', a.place) this.close(ws, RELAY_CLOSE_CODE.BAD_OUTER_CREDENTIAL, 'relay authorization expired') await this.onSocketGone(ws, RELAY_CLOSE_CODE.BAD_OUTER_CREDENTIAL, '') continue diff --git a/cloud/apps/relay-edge/src/metrics.ts b/cloud/apps/relay-edge/src/metrics.ts index 7d87b759e4d..febc2bab77c 100644 --- a/cloud/apps/relay-edge/src/metrics.ts +++ b/cloud/apps/relay-edge/src/metrics.ts @@ -2,6 +2,7 @@ import type { Env } from './env' export type MetricEvent = + // label 'new' | 'rebind'; reason 'keepalive' | 'legacy' (took the keepalive offer or not). | 'control_active' | 'control_close' | 'phone_open' @@ -26,6 +27,7 @@ export type MetricEvent = | 'control_upgrade' // Control closed 4401 for expired authorization: value = seconds since its last extending // refresh, label 'refreshed'; -1 and label 'never' when this socket never extended its token. + // double2 = seconds since the host's last inbound frame or keepalive; reason 'keepalive' | 'legacy'. | 'auth_expired_close' // Pre-auth socket refused by the per-source limiter: label 'phone' | 'data' | 'health'. Unpushed-host phones: 'not_on_edge'. | 'preauth_limited' diff --git a/cloud/apps/relay/src/edge-relay-cohort.ts b/cloud/apps/relay/src/edge-relay-cohort.ts index 5227e8f9ff4..d6a8818c55d 100644 --- a/cloud/apps/relay/src/edge-relay-cohort.ts +++ b/cloud/apps/relay/src/edge-relay-cohort.ts @@ -50,18 +50,18 @@ export function edgeCohortBucketPermille(relayHostId: string): number { } // Mode off or down empties the cohort. Otherwise deny wins, then host allow, then region scope; -// within the region, account allow or the rollout share. +// within the region, account allow or the rollout share. Region 'any' skips the region scope. export function inEdgeCohort( config: EdgeRelayConfig, relayHostId: string, - region: RelayRegion | undefined, + region: RelayRegion | undefined | 'any', userId?: string ): boolean { const flags = config.control?.() ?? EDGE_CONTROL_DEFAULTS if (flags.mode !== 'on') { return false } if (config.denyHosts.has(relayHostId)) { return false } if (config.allowHosts.has(relayHostId)) { return true } - if (!config.regions.has(region ?? RELAY_DEFAULT_REGION)) { return false } + if (region !== 'any' && !config.regions.has(region ?? RELAY_DEFAULT_REGION)) { return false } if (userId !== undefined && config.allowUsers?.has(userId)) { return true } return edgeCohortBucketPermille(relayHostId) < edgeRolloutPermille(config.rolloutPercent, flags) } diff --git a/cloud/apps/relay/src/edge-relay-evacuation.test.ts b/cloud/apps/relay/src/edge-relay-evacuation.test.ts index 9b671710f28..855eb2ea55f 100644 --- a/cloud/apps/relay/src/edge-relay-evacuation.test.ts +++ b/cloud/apps/relay/src/edge-relay-evacuation.test.ts @@ -108,6 +108,22 @@ describe('edge evacuation under runtime control', () => { h.evacuation.stop() }) + it('leaves region scope to the assign path: a stored preference outside it drains nobody', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const flags: EdgeControlFlags = { mode: 'on', rolloutPermille: 1000 } + const h = await harness({ control: () => flags }) + // On the edge by its ask (no region, or us-central1); its stored preference says otherwise. + await h.insert(hostId(1)) + await h.prefer(hostId(1), 'asia-east2') + await h.insert(hostId(2)) + expect(await h.evacuation.sweep()).toBe(0) + expect(h.admin.drained).toEqual([]) + // Leaving the cohort still drains, whatever the stored region. + flags.rolloutPermille = 0 + expect(await h.evacuation.sweep()).toBe(2) + expect(h.admin.drained.sort()).toEqual([hostId(1), hostId(2)]) + }) + it(`sends at most ${EDGE_EVACUATION_CONCURRENCY} drains at once`, async () => { vi.spyOn(console, 'warn').mockImplementation(() => {}) const h = await harness() diff --git a/cloud/apps/relay/src/edge-relay-evacuation.ts b/cloud/apps/relay/src/edge-relay-evacuation.ts index ae1c31f5056..db103f67c55 100644 --- a/cloud/apps/relay/src/edge-relay-evacuation.ts +++ b/cloud/apps/relay/src/edge-relay-evacuation.ts @@ -3,7 +3,6 @@ // rows whose host is no longer in the cohort and asks the edge to drain them; the desktop then // re-asks /v1/assign, and that ask exports its data and places it on a cell (app.ts). Each pass also // retries fences that did not land after a host left (edge-relay-fence.ts). -import { RELAY_DEFAULT_REGION, RelayRegionSchema } from '@orca-cloud/relay-contract/relay-regions' import type { RelayDatabase } from './database/database.js' import { EdgeAdminUnavailableError, type EdgeAdmin } from './edge-admin-client.js' import { inEdgeCohort, text, type EdgeRelayConfig, type Identity } from './edge-relay-cohort.js' @@ -116,9 +115,11 @@ export class EdgeEvacuation { for (const row of rows) { const identity = { userId: text(row, 'user_id'), relayHostId: text(row, 'relay_host_id') } pass.cursor = identity - const stored = RelayRegionSchema.safeParse(row.preferred_region) - const region = stored.success ? stored.data : RELAY_DEFAULT_REGION - if (inEdgeCohort(this.config, identity.relayHostId, region, identity.userId)) { continue } + // Region scope is the assign path's call alone: it decides with the region the desktop + // asks for, which the stored preference can miss or lag. Judging it here too drained + // hosts that the next ask put straight back (a drain every few minutes). A host that asks + // for a region outside the scope leaves on that ask. + if (inEdgeCohort(this.config, identity.relayHostId, 'any', identity.userId)) { continue } if (this.drainedAt.has(drainKey(identity))) { continue } leaving.push(identity) // Resume after the last host taken, so the rest of the page is read next tick. @@ -143,10 +144,8 @@ export class EdgeEvacuation { private async readPage(pass: Pass) { const { cursor, origin, wrapped } = pass return await this.database.query( - `SELECT a.user_id, a.relay_host_id, p.preferred_region + `SELECT a.user_id, a.relay_host_id FROM relay_assignments a - LEFT JOIN relay_assignment_region_preferences p - ON p.user_id = a.user_id AND p.relay_host_id = a.relay_host_id WHERE a.cell_id = ? AND (a.user_id > ? OR (a.user_id = ? AND a.relay_host_id > ?)) ${wrapped ? 'AND (a.user_id < ? OR (a.user_id = ? AND a.relay_host_id <= ?))' : ''} ORDER BY a.user_id, a.relay_host_id diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 8ee00e478c2..362d8073cc6 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -627,12 +627,7 @@ 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 2 test-no-wall-clock:src/renderer/src/components/dashboard/useLiveDashboardSnapshot.test.ts -1 test-no-wall-clock:src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.opening-send.test.tsx -1 test-no-wall-clock:src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.queued-turn-order.test.tsx -2 test-no-wall-clock:src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-indicator.test.tsx 3 test-no-wall-clock:src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx -1 test-no-wall-clock:src/renderer/src/components/native-chat/session/structured/delivery/NativeChatMessageList.unsent-message.test.tsx -3 test-no-wall-clock:src/renderer/src/components/native-chat/surfaces/integration/NativeChatMessageList.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 @@ -642,11 +637,8 @@ 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 1 test-no-wall-clock:src/renderer/src/components/worktree-jump/WorktreeJumpPalette.recent-tabs.behavior.test.tsx -4 test-no-wall-clock:src/renderer/src/components/worktree-jump/WorktreeJumpPalette.recent-tabs.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/paired-runtime-closed-tab-resume.test.ts -2 test-no-wall-clock:src/renderer/src/lib/use-tab-agent-observed-signal-dispatch.test.tsx -2 test-no-wall-clock:src/renderer/src/lib/wake-sleeping-agents-live-unmounted-pane.test.ts +2 test-no-wall-clock:src/renderer/src/lib/agent-session/tab-identity/use-tab-agent-observed-signal-dispatch.test.tsx 1 test-no-wall-clock:src/renderer/src/lib/workspace/ownership/workspace-terminal-host-authority.test.ts 1 test-no-wall-clock:src/renderer/src/lib/workspace/activation/worktree-activation-emptied-workspace-reseed.test.ts 2 test-no-wall-clock:src/renderer/src/store/github/pull-requests/github-pr-branch-linked-pr-divergence.test.ts diff --git a/config/focus-setting-read-baseline.txt b/config/focus-setting-read-baseline.txt index f907d5d4bef..7fc0cfa7341 100644 --- a/config/focus-setting-read-baseline.txt +++ b/config/focus-setting-read-baseline.txt @@ -220,20 +220,20 @@ 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/client-creation-action-error.ts -2 src/renderer/src/lib/client-creation-action-policy.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/launch-ai-vault-session.ts -1 src/renderer/src/lib/local-preflight-context.ts +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/lib/runtime-session-mirror-targets.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/lib/unread-badge-count-selector.ts +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 diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 36b07604a3e..3437945403d 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -479,7 +479,7 @@ 2 src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.ts 1 src/main/runtime/orchestration/db/runtime-orchestration-database-access.ts 2 src/main/runtime/push/push-unregister-outbox.ts -2 src/main/runtime/rpc/methods/mobile-delivery/bundled-mobile-web-bundle.ts +1 src/main/runtime/rpc/methods/mobile-delivery/bundled-mobile-web-bundle.ts 1 src/main/runtime/rpc/server/network-source-policy-store.ts 2 src/main/runtime/rpc/server/pairing/device-registry-corruption.ts 2 src/main/runtime/rpc/server/pairing/device-registry-disk-merge.ts diff --git a/config/mobile-localization-coverage-allowlist.json b/config/mobile-localization-coverage-allowlist.json index 113c65c34da..594bc0a7919 100644 --- a/config/mobile-localization-coverage-allowlist.json +++ b/config/mobile-localization-coverage-allowlist.json @@ -42,70 +42,70 @@ "count": 1 }, { - "filePath": "mobile/src/components/accounts-snapshot.ts", + "filePath": "mobile/src/accounts/accounts-snapshot.ts", "kind": "object-property:message", "text": "Claude limits use the wrong provider identity", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/components/accounts-snapshot.ts", + "filePath": "mobile/src/accounts/accounts-snapshot.ts", "kind": "object-property:message", "text": "Codex limits use the wrong provider identity", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/components/accounts-snapshot.ts", + "filePath": "mobile/src/accounts/accounts-snapshot.ts", "kind": "object-property:message", "text": "Host Codex accounts cannot name a WSL distro", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/components/accounts-snapshot.ts", + "filePath": "mobile/src/accounts/accounts-snapshot.ts", "kind": "object-property:message", "text": "Host rate-limit targets cannot name a WSL distro", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/components/accounts-snapshot.ts", + "filePath": "mobile/src/accounts/accounts-snapshot.ts", "kind": "object-property:message", "text": "Inactive Claude limits use the wrong provider identity", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/components/accounts-snapshot.ts", + "filePath": "mobile/src/accounts/accounts-snapshot.ts", "kind": "object-property:message", "text": "Inactive Codex limits use the wrong provider identity", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/components/accounts-snapshot.ts", + "filePath": "mobile/src/accounts/accounts-snapshot.ts", "kind": "object-property:message", "text": "WSL Codex accounts require an exact distro", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/components/accounts-snapshot.ts", + "filePath": "mobile/src/accounts/accounts-snapshot.ts", "kind": "object-property:message", "text": "WSL rate-limit targets require an exact distro", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/components/codex-reset-credit-reply-schema.ts", + "filePath": "mobile/src/accounts/usage/codex-reset-credit-reply-schema.ts", "kind": "object-property:message", "text": "Host reset scopes cannot name a WSL distro", "dynamic": false, "count": 1 }, { - "filePath": "mobile/src/components/codex-reset-credit-reply-schema.ts", + "filePath": "mobile/src/accounts/usage/codex-reset-credit-reply-schema.ts", "kind": "object-property:message", "text": "WSL reset scopes require an exact distro", "dynamic": false, diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 90b27e1136b..852bc9e138b 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -1223,12 +1223,12 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["remote-runtime"], - "coveredPlatforms": ["macos", "linux"], + "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit1348 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): Real authenticated sockets plus isolated desktop and headless hosts with desktop and browser viewers; deterministic lifecycle tests cover stale results and reader deadlines. The test-value audit removes the standalone runtime-status-snapshot.test.ts example that immediately applied the same supplied snapshots to two isolated slice stores. Its direct sequence-2 then older unavailable sequence-1 acceptance/rejection alarm is intentionally lost; it did not exercise a pending read, subscription delivery or a shared viewer connection. The suite retains failed-verification/recovery, disconnect/pairing retirement and catalog-refresh replay examples, which are not equivalent replacements. Historical executed commands, counts and results remain unchanged; no new live host, process restart or platform evidence is claimed. Audit1348: src/main/ipc/runtime-environments/runtime-environment-status-recovery.test.ts removed. Startup retry/broadcast counts and passive-before-active bootstrap request count. 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. The current assertion index names unchanged owner lifecycle tests from the successful focused run. They do not replace the deleted startup retry/broadcast count alarms. 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. Audit1748 removes7 of13 authored host-status-owner definitions: request/polling counts, reconnect/no-request variants, deadline copy and blocked-reason projections. Lost alarms are intentional; no equivalent replacement coverage is claimed. Existing dated evidenceRuns are historical and unchanged, and do not validate this reduced source or current aggregate selectors. Focused candidate execution, if successful, validates only the retained local fake-request/clock tests, not authenticated sockets, rendered clients or platform parity.", + "coverageNotes": "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. Audit1348 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): Real authenticated sockets plus isolated desktop and headless hosts with desktop and browser viewers; deterministic lifecycle tests cover stale results and reader deadlines. The test-value audit removes the standalone runtime-status-snapshot.test.ts example that immediately applied the same supplied snapshots to two isolated slice stores. Its direct sequence-2 then older unavailable sequence-1 acceptance/rejection alarm is intentionally lost; it did not exercise a pending read, subscription delivery or a shared viewer connection. The suite retains failed-verification/recovery, disconnect/pairing retirement and catalog-refresh replay examples, which are not equivalent replacements. Historical executed commands, counts and results remain unchanged; no new live host, process restart or platform evidence is claimed. Audit1348: src/main/ipc/runtime-environments/runtime-environment-status-recovery.test.ts removed. Startup retry/broadcast counts and passive-before-active bootstrap request count. 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. The current assertion index names unchanged owner lifecycle tests from the successful focused run. They do not replace the deleted startup retry/broadcast count alarms. 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. Audit1748 removes7 of13 authored host-status-owner definitions: request/polling counts, reconnect/no-request variants, deadline copy and blocked-reason projections. Lost alarms are intentional; no equivalent replacement coverage is claimed. Existing dated evidenceRuns are historical and unchanged, and do not validate this reduced source or current aggregate selectors. Focused candidate execution, if successful, validates only the retained local fake-request/clock tests, not authenticated sockets, rendered clients or platform parity.", "motivatingLinks": ["https://github.com/stablyai/orca/pull/19163"], "invariant": "Failed bootstrap and authenticated reconnect converge without UI triggers; one connection owner publishes verified status, with no independent healthy status polling.", - "oracle": "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.", + "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 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" @@ -1258,26 +1258,6 @@ "result": "passed", "summary": "Desktop-host and headless-host journeys passed with desktop and browser viewers.", "durationSeconds": 31.3 - }, - { - "date": "2026-11-04", - "runner": "local", - "platform": "linux", - "result": "passed", - "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm --config.verifyDepsBeforeRun=false test src/main/ipc/runtime-environments/runtime-environment-status-connection.test.ts src/renderer/src/store/slices/runtime-status-snapshot.test.ts src/renderer/src/web/web-runtime-status-owner.test.ts src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts --maxWorkers=2", - "currentCommand": "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", - "durationSeconds": 4.37, - "summary": "Test Files 4 passed (4); Tests 22 passed (22). Focused Linux unit execution; no physical-provider, p95 or cross-platform claim. Source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e." - }, - { - "date": "2026-11-04", - "runner": "local", - "platform": "linux", - "result": "passed", - "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm --config.verifyDepsBeforeRun=false test src/main/ipc/runtime-environments/runtime-environment-status-connection.test.ts src/renderer/src/store/slices/runtime-status-snapshot.test.ts src/renderer/src/web/web-runtime-status-owner.test.ts src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts --maxWorkers=2", - "currentCommand": "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", - "durationSeconds": 4.52, - "summary": "Test Files 4 passed (4); Tests 22 passed (22). Focused Linux unit execution; no physical-provider, p95 or cross-platform claim. Source head 415c9cffc2d10024131ec4b6721767a22195de6d." } ], "runtimeBudget": { @@ -1305,7 +1285,10 @@ "The test-value audit removes the standalone runtime-status-snapshot.test.ts example that immediately applied the same supplied snapshots to two isolated slice stores. Its direct sequence-2 then older unavailable sequence-1 acceptance/rejection alarm is intentionally lost; it did not exercise a pending read, subscription delivery or a shared viewer connection. The suite retains failed-verification/recovery, disconnect/pairing retirement and catalog-refresh replay examples, which are not equivalent replacements. Historical executed commands, counts and results remain unchanged; no new live host, process restart or platform evidence is claimed.", "Audit1348: src/main/ipc/runtime-environments/runtime-environment-status-recovery.test.ts removed. Startup retry/broadcast counts and passive-before-active bootstrap request count. No equivalent replacement coverage is claimed.", "Audit1348 historical platform/provider scope before source changes: {\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"remote-runtime\"]}. Remaining provider scope applies only to unchanged-source receipts.", - "Audit1348 historical assertion inventory for deleted/reduced sources; not current validated assertions:\n[\n {\n \"file\": \"src/main/ipc/runtime-environments/runtime-environment-status-recovery.test.ts\",\n \"assertions\": [\n \"recovers a saved host after its first status check fails, without another UI request\"\n ]\n }\n]" + "Audit1348 historical assertion inventory for deleted/reduced sources; not current validated assertions:\n[\n {\n \"file\": \"src/main/ipc/runtime-environments/runtime-environment-status-recovery.test.ts\",\n \"assertions\": [\n \"recovers a saved host after its first status check fails, without another UI request\"\n ]\n }\n]", + "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.", + "Audit 3301 retires this complete dated unit receipt because runtime-status-snapshot.test.ts was reduced. Its original command, result and counts remain historical and do not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-11-04\",\n \"runner\": \"local\",\n \"platform\": \"linux\",\n \"result\": \"passed\",\n \"command\": \"ORCA_BACKGROUND_LAUNCH=1 pnpm --config.verifyDepsBeforeRun=false test src/main/ipc/runtime-environments/runtime-environment-status-connection.test.ts src/renderer/src/store/slices/runtime-status-snapshot.test.ts src/renderer/src/web/web-runtime-status-owner.test.ts src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts --maxWorkers=2\",\n \"currentCommand\": \"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\",\n \"durationSeconds\": 4.37,\n \"summary\": \"Test Files 4 passed (4); Tests 22 passed (22). Focused Linux unit execution; no physical-provider, p95 or cross-platform claim. Source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e.\"\n }", + "Audit 3301 retires this complete dated unit receipt because runtime-status-snapshot.test.ts was reduced. Its original command, result and counts remain historical and do not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-11-04\",\n \"runner\": \"local\",\n \"platform\": \"linux\",\n \"result\": \"passed\",\n \"command\": \"ORCA_BACKGROUND_LAUNCH=1 pnpm --config.verifyDepsBeforeRun=false test src/main/ipc/runtime-environments/runtime-environment-status-connection.test.ts src/renderer/src/store/slices/runtime-status-snapshot.test.ts src/renderer/src/web/web-runtime-status-owner.test.ts src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts --maxWorkers=2\",\n \"currentCommand\": \"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\",\n \"durationSeconds\": 4.52,\n \"summary\": \"Test Files 4 passed (4); Tests 22 passed (22). Focused Linux unit execution; no physical-provider, p95 or cross-platform claim. Source head 415c9cffc2d10024131ec4b6721767a22195de6d.\"\n }" ], "demotionRule": "Keep experimental until repeated runs establish reliability; preserve request-count and lifecycle assertions." }, @@ -2349,30 +2332,30 @@ "providers": ["local", "ssh", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "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": "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": "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": "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", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/workspace/search/palette/cmd-j-host-qualified-candidate-ownership.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts src/shared/workspace-session/workspace-session-schema.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/simulator-tab-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-tabs-sync-mirror-identity.test.ts src/shared/workspace-session/workspace-session-schema.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/simulator-tab-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-tabs-sync-mirror-identity.test.ts src/shared/workspace-session/workspace-session-schema.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/simulator-tab-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-tabs-sync-mirror-identity.test.ts src/shared/workspace-session/workspace-session-schema.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/workspace/search/palette/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/simulator-tab-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-tabs-sync-mirror-identity.test.ts src/shared/workspace-session/workspace-session-schema.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx src/renderer/src/lib/workspace/search/palette/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/simulator-tab-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-tabs-sync-mirror-identity.test.ts src/shared/workspace-session/workspace-session-schema.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx src/renderer/src/lib/workspace/search/palette/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/simulator-tab-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-tabs-sync-mirror-identity.test.ts src/shared/workspace-session/workspace-session-schema.test.ts", "pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], "testFiles": [ "src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts", "src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx", - "src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts", + "src/renderer/src/lib/workspace/search/palette/cmd-j-host-qualified-candidate-ownership.test.ts", "src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts", "src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts", "src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts", @@ -2388,9 +2371,8 @@ "file": "src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts", "assertions": ["same-id local and SSH worktrees keep separate review-index results"] }, - { - "file": "src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts", + "file": "src/renderer/src/lib/workspace/search/palette/cmd-j-host-qualified-candidate-ownership.test.ts", "assertions": [ "scoped open-tab search keeps a hidden same-id sibling in the legacy ownership ambiguity set" ] @@ -2426,7 +2408,7 @@ "result": "failed", "durationSeconds": 1.8, "summary": "The first review-round oracle failed 4/40: browser and simulator dropped the SSH worktree's paired-runtime-owned tab, generic workspace rows attributed the remote tab to local, and active local tab creation left ownership unstamped. Historical command and result are preserved after the test-value audit removed the tab-store assertions this run included. currentCommand is only an administrative link to the remaining gate command; the historical run has not validated that command or equivalent coverage.", - "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts" + "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/workspace/search/palette/cmd-j-host-qualified-candidate-ownership.test.ts" }, { "date": "2026-08-20", @@ -2478,7 +2460,6 @@ "summary": "The final clean-round fail-closed oracle failed 1/7 before the follow-up: an unavailable explicit runtime owner borrowed physical SSH repository metadata. Historical command preserved after the test-value audit removed the palette repo resolver suite. currentCommand is an administrative link to a remaining gate command; this historical run has not validated that command or equivalent coverage.", "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts" }, - { "date": "2026-08-20", "runner": "local", @@ -2566,7 +2547,9 @@ "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. Historical removed assertion inventory: [{\"file\":\"src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts\",\"assertions\":[\"preserves a sibling runtime mirror under the same bare worktree id\"]}]", "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.", "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.", - "Audit2192 retires the removed physical-SSH repository badge assertion from WorktreeJumpPalette.test.tsx and its exact historical failed oracle receipt. Current reduced test selectors and unrelated unit/E2E receipts remain; none was rerun by this source audit and equivalent coverage is not claimed. Original obsolete assertion object verbatim:\n{\n \"file\": \"src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx\",\n \"assertions\": [\n \"a runtime-owned worktree row never renders repository metadata borrowed from its physical SSH host\"\n ]\n }\nOriginal dated failed receipt object verbatim:\n{\n \"date\": \"2026-08-20\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/WorktreeJumpPalette.test.tsx\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx\",\n \"result\": \"failed\",\n \"durationSeconds\": 5.1,\n \"summary\": \"With the component's physical-host prelookup restored, the rendered palette oracle failed 1/12: the runtime-owned row displayed the physical SSH repository badge.\"\n }" + "Audit2192 retires the removed physical-SSH repository badge assertion from WorktreeJumpPalette.test.tsx and its exact historical failed oracle receipt. Current reduced test selectors and unrelated unit/E2E receipts remain; none was rerun by this source audit and equivalent coverage is not claimed. Original obsolete assertion object verbatim:\n{\n \"file\": \"src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx\",\n \"assertions\": [\n \"a runtime-owned worktree row never renders repository metadata borrowed from its physical SSH host\"\n ]\n }\nOriginal dated failed receipt object verbatim:\n{\n \"date\": \"2026-08-20\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/WorktreeJumpPalette.test.tsx\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx\",\n \"result\": \"failed\",\n \"durationSeconds\": 5.1,\n \"summary\": \"With the component's physical-host prelookup restored, the rendered palette oracle failed 1/12: the runtime-owned row displayed the physical SSH repository badge.\"\n }", + "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 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." ], "demotionRule": "Cannot promote if a same-id sibling tab duplicates, disappears, activates another host, or if ambiguous unstamped ownership is guessed." }, @@ -2587,14 +2570,14 @@ "providers": ["orca-server", "direct-ssh"], "coveredPlatforms": ["macos"], "coveredProviders": ["orca-server", "direct-ssh"], - "coverageNotes": "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. 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/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n } Historical prior account (preserved verbatim): 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: Audit1441 removes the complete renderer VM-runtime settings suite: display filter/status/SSH-retry flags, cleanup and stop RPC-to-toast/dialog plumbing, manual-copy plumbing and polling toast silence. The suite did not execute provider teardown or process cancellation. Its rendered stop/retry and hidden-SSH display alarms are intentionally retired; no equivalent replacement or fresh reduced-selector runtime 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/lib/ephemeral-vm-workspace-target.test.ts: Loses wrapper-level host rebinding, incompatible provisioned-root refusal and best-effort cleanup-call alarms; all are mock-only orchestration projections. 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): A pinned exact-source harness runs the pre-#14352 reader and lifecycle service against baseline, affected-main, candidate, and fix-reverted stores. Platform-neutral tests cover store compatibility, user-cancellable cleanup, branch/ref adoption; audit885 removes the direct resume ownership predicate alarms. The direct-SSH provisioned-root Electron journey remains the live transport and destroy proof; this desktop sidecar is not mobile-facing and changes no RPC or remote wire payload. The test-value audit removed the renderer provisioned-root create-options suite. Its two incomplete-identity rejection assertions are lost: one omitted workspaceRunContext and other identity fields, and one supplied the context but omitted ephemeralVmExpectedRefHead. The suite did not test successful option mapping. Retained source-ref and lifecycle suites do not establish equivalent renderer guard coverage. Audit1342: src/renderer/src/lib/ephemeral-vm-runtime-cleanup.test.ts removed. Runtime/SSH ownership, encoded target, retry/failure/listing-error cleanup projection samples disappear. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit 3292 retires the direct-SSH failed-project retention, managed-server failed-project retention and ordinary confirmed managed-VM destruction/no-repo.rm examples from repos-ephemeral-vm-cleanup-retention.test.ts. Host-scoped same-workspace isolation and stale renderer catalog reconciliation remain byte-identical. These three supplied-result alarms are intentionally lost without equivalent replacement. Existing selectors/assertionRefs, unrelated cross-version rollback receipt and archived complete 122-case cleanup receipt remain exact; no fresh broad runtime, provider, platform or mixed-version result is claimed. Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. 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/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n } Historical prior account (preserved verbatim): 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: Audit1441 removes the complete renderer VM-runtime settings suite: display filter/status/SSH-retry flags, cleanup and stop RPC-to-toast/dialog plumbing, manual-copy plumbing and polling toast silence. The suite did not execute provider teardown or process cancellation. Its rendered stop/retry and hidden-SSH display alarms are intentionally retired; no equivalent replacement or fresh reduced-selector runtime 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/lib/ephemeral-vm-workspace-target.test.ts: Loses wrapper-level host rebinding, incompatible provisioned-root refusal and best-effort cleanup-call alarms; all are mock-only orchestration projections. 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): A pinned exact-source harness runs the pre-#14352 reader and lifecycle service against baseline, affected-main, candidate, and fix-reverted stores. Platform-neutral tests cover store compatibility, user-cancellable cleanup, branch/ref adoption; audit885 removes the direct resume ownership predicate alarms. The direct-SSH provisioned-root Electron journey remains the live transport and destroy proof; this desktop sidecar is not mobile-facing and changes no RPC or remote wire payload. The test-value audit removed the renderer provisioned-root create-options suite. Its two incomplete-identity rejection assertions are lost: one omitted workspaceRunContext and other identity fields, and one supplied the context but omitted ephemeralVmExpectedRefHead. The suite did not test successful option mapping. Retained source-ref and lifecycle suites do not establish equivalent renderer guard coverage. Audit1342: src/renderer/src/lib/ephemeral-vm-runtime-cleanup.test.ts removed. Runtime/SSH ownership, encoded target, retry/failure/listing-error cleanup projection samples disappear. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4274", "https://github.com/stablyai/orca/pull/14352", "https://github.com/stablyai/orca/issues/13044" ], "invariant": "A sidecar written by the new build cannot make the previous production build lose otherwise compatible VM runtimes. Downgrade lifecycle writes remain authoritative after re-upgrade, provisioned-root metadata remains recoverable, and corrupt or future feature metadata is preserved without poisoning the rollback-readable v1 store. Destroy attempts have no automatic wall-clock cutoff; a user stop terminates the process tree, retains cleanup ownership, and permits a fresh retry. Provider failure retains the SSH/project context needed for safe cleanup. Unrecoverable recipe context releases only the hidden SSH registration while preserving lifecycle/provider metadata. Provisioned-root create receives the source ref's pinned commit, adoption verifies the requested branch/ref, and resume preserves the connection mode plus stable SSH ownership identity while allowing endpoint rotation.", - "oracle": "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. 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/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n } 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): Write one ordinary schema-v1 runtime and one provisioned-root runtime. Require the exact pre-#14352 reader to return both, run the old destroy lifecycle against the projected provisioned record, then require the candidate to retain the cleaned state while restoring schema-v2 and checkout-mode metadata. The same old reader must reject affected-main and fix-reverted bytes. Malformed, oversized, unknown-record, and future-version feature sidecars must leave rollback-compatible records accessible and must not be overwritten during compatible lifecycle mutations. Require destroy to have no implicit deadline, stop a hung destroy through the public desktop action, require cleanup_failed plus a fresh successful retry, prove provider or project-host rollback failure retains every ownership record required to retry, and prove missing recipe context cannot leave an unremovable hidden SSH registration. Supply the source ref's captured commit to create, reject a provisioned checkout on the wrong branch/ref, and reject a resume that changes connection mode or SSH ownership.", + "oracle": "Audit 3292 retires the direct-SSH failed-project retention, managed-server failed-project retention and ordinary confirmed managed-VM destruction/no-repo.rm examples from repos-ephemeral-vm-cleanup-retention.test.ts. Host-scoped same-workspace isolation and stale renderer catalog reconciliation remain byte-identical. These three supplied-result alarms are intentionally lost without equivalent replacement. Existing selectors/assertionRefs, unrelated cross-version rollback receipt and archived complete 122-case cleanup receipt remain exact; no fresh broad runtime, provider, platform or mixed-version result is claimed. Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. 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/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n } 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): Write one ordinary schema-v1 runtime and one provisioned-root runtime. Require the exact pre-#14352 reader to return both, run the old destroy lifecycle against the projected provisioned record, then require the candidate to retain the cleaned state while restoring schema-v2 and checkout-mode metadata. The same old reader must reject affected-main and fix-reverted bytes. Malformed, oversized, unknown-record, and future-version feature sidecars must leave rollback-compatible records accessible and must not be overwritten during compatible lifecycle mutations. Require destroy to have no implicit deadline, stop a hung destroy through the public desktop action, require cleanup_failed plus a fresh successful retry, prove provider or project-host rollback failure retains every ownership record required to retry, and prove missing recipe context cannot leave an unremovable hidden SSH registration. Supply the source ref's captured commit to create, reject a provisioned checkout on the wrong branch/ref, and reject a resume that changes connection mode or SSH ownership.", "commands": [ "node config/scripts/runtime-verification/ephemeral-store/run-ephemeral-vm-runtime-store-rollback-repro.mjs config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/shared/ephemeral-vm-runtime-store.test.ts src/shared/ephemeral-vm-runtime-store-rollback.test.ts src/shared/ephemeral-vm-recipe-process.test.ts src/main/ephemeral-vm/runtime-service.test.ts src/main/ephemeral-vm/recipe-runner.test.ts src/main/ephemeral-vm/runtime-ssh-cleanup.test.ts src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts src/main/ipc/ephemeral-vm-provision-cancel.test.ts src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts src/main/ipc/ephemeral-vm.test.ts src/renderer/src/store/repos/repos-ephemeral-vm-cleanup-retention.test.ts", @@ -2721,7 +2704,8 @@ "Audit1417 intentionally deletes src/renderer/src/lib/ephemeral-vm-workspace-target.test.ts: Loses wrapper-level host rebinding, incompatible provisioned-root refusal and best-effort cleanup-call alarms; all are mock-only orchestration projections. No equivalent replacement coverage or fresh result is claimed.", "Audit1853 accepts removal of the runtime-ssh-cleanup.test.ts alarm for repairing cleanup_failed/provider-succeeded records that already lack a target ID. No equivalent replacement coverage is claimed. Keep the surviving cleanup selector and unchanged cross-version rollback receipt; the historical 2026-08-14 122-case cleanup receipt remains archived verbatim in knownGaps.", "Audit1863 removes the standalone default-source-ref provisioning example. Its direct default-ref pinning alarm is intentionally lost; selected-ref pinning and invalid-ref cases remain without an equivalent replacement claim. Focused survivor execution does not validate the broad rollback selector or physical cross-version provisioning. Existing receipts retain their original commands and counts.", - "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. 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/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n }" + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. 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/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n }", + "Audit 3292 retires the direct-SSH failed-project retention, managed-server failed-project retention and ordinary confirmed managed-VM destruction/no-repo.rm examples from repos-ephemeral-vm-cleanup-retention.test.ts. Host-scoped same-workspace isolation and stale renderer catalog reconciliation remain byte-identical. These three supplied-result alarms are intentionally lost without equivalent replacement. Existing selectors/assertionRefs, unrelated cross-version rollback receipt and archived complete 122-case cleanup receipt remain exact; no fresh broad runtime, provider, platform or mixed-version result is claimed." ], "demotionRule": "Demote if a new write fails the pinned rollback reader, a downgrade lifecycle mutation is lost after re-upgrade, malformed/future metadata overwrites recoverable bytes, ordinary v1 bytes change, user stop cannot settle a destroy process tree, cleanup loses retry ownership, an unrecoverable context leaves a permanent hidden SSH registration, or the focused gate flakes without an identified harness defect." }, @@ -4202,10 +4186,10 @@ "providers": ["remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["remote-runtime"], - "coverageNotes": "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": "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": "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": "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" @@ -4306,7 +4290,12 @@ "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.", "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.", "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.", - "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." + "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.", + "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.", + "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 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 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 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." ], "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." }, @@ -4424,7 +4413,7 @@ "providers": ["remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "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": "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", @@ -4435,7 +4424,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": "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": "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 src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-browser-tabs.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", @@ -4446,8 +4435,8 @@ "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", "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", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts", - "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/doc-preview-document-actions.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", - "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/doc-preview-document-actions.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", + "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", + "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", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/link-actions/LinkActionPopover.test.tsx src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-editor-diff-tabs.test.ts", "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", "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", @@ -4473,7 +4462,6 @@ "src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.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/renderer/src/components/browser-pane/workspace-doc/doc-preview-document-actions.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", "src/shared/document-preview/doc-preview-scheme.test.ts", @@ -4937,7 +4925,9 @@ "D01 final candidate whole-registration policy removes retired module selectors and obsolete assertion descriptions prospectively. Existing unaffected receipts retain their original scope; reduced selectors have no new execution or equivalent replacement claim. Retired named modules: [\"src/preload/doc-preview-link-interception.test.ts\",\"src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx\"]. Retired compound assertion refs, preserved as historical data: [{\"file\":\"src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts\",\"assertions\":[\"an external preview link shows the reader its exact destination and becomes a browser tab only after confirmation\",\"a declined confirmation opens nothing, and a confirmed tab that is refused or fails outright surfaces instead of being dropped\"]}]", "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. Retired assertion reference: {\"file\":\"src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts\",\"assertions\":[\"closing an absent renderer page returns browser_tab_not_found instead of an untyped failure\"]}", "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.", - "File/document owner layout retires the complete workspace-doc-address-input unit suite because its sole mixed case asserts internal catalog-enumeration work. The current-workspace HTML-resolution alarm is lost; no equivalent replacement coverage or pass for the reduced unit selector is claimed. Historical receipts and all remaining selectors/assertions retain their original scope." + "File/document owner layout retires the complete workspace-doc-address-input unit suite because its sole mixed case asserts internal catalog-enumeration work. The current-workspace HTML-resolution alarm is lost; no equivalent replacement coverage or pass for the reduced unit selector is claimed. Historical receipts and all remaining selectors/assertions retain their original scope.", + "Module-layout wave2 intentionally retires complete prohibited owning registrations in src/renderer/src/components/browser-pane/workspace-doc/doc-preview-document-actions.test.ts. Lost alarms: A resolved remote file owner taking precedence over an unresolved workspace owner would lose its routing alarm. A project published on two hosts refusing to open an ambiguous local copy would lose its refusal alarm. An unresolved document refusing both local open and remote download, and including its path in the refusal, would lose the existing alarm. An unknown workspace root preventing an accidental local document open would lose its guard alarm. A restored document using its recorded runtime owner when the worktree resolves none would lose its existing fallback alarm. A restored tab without a recorded owner consulting the resolved worktree owner would lose its existing fallback alarm. No equivalent replacement coverage or reduced-selector pass 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." ], "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." }, @@ -7322,7 +7312,7 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "ssh", "wsl", "remote-runtime"], - "coverageNotes": "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": "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", @@ -7332,7 +7322,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": "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": "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 src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-session-launch.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-handoff.test.ts", @@ -7591,7 +7581,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.", "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. Original prospective command before removal: 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 src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-session-launch.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-handoff.test.ts src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts src/renderer/src/runtime/web-session-tabs-sync/inventory/web-runtime-session.test.ts", - "Module-layout wave1 intentionally retires complete prohibited owning registrations in src/renderer/src/runtime/web-session-tabs-sync/inventory/web-runtime-session.test.ts. Lost alarms: confirms only the exact handoff after its post-create list completes. No equivalent replacement coverage or pass for a reduced selector is claimed. All unrelated selectors and historical receipts retain their original scope." + "Module-layout wave1 intentionally retires complete prohibited owning registrations in src/renderer/src/runtime/web-session-tabs-sync/inventory/web-runtime-session.test.ts. Lost alarms: confirms only the exact handoff after its post-create list completes. No equivalent replacement coverage or pass for a reduced selector is claimed. All unrelated selectors and historical receipts retain their original scope.", + "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." ], "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." }, @@ -7624,7 +7615,7 @@ "oracle": "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/settings/settings.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/lib/resolved-worktree-execution-host.test.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/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" @@ -7633,10 +7624,8 @@ "src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts", "src/renderer/src/store/slices/settings/settings.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", - "src/renderer/src/lib/resolved-worktree-execution-host.test.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", @@ -7801,7 +7790,8 @@ "Audit1488 deletes NonGitFolderDialog tests. The hand-assembled scan/import pipelines, supplied host and folder outcomes, registration callback receipts and static host confirmation alarms are retired. No equivalent replacement coverage or fresh routing validation is claimed. Historical receipts and assertions describe their original sources only.", "Audit1488 historical assertion inventory; not current validated assertions: []", "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.", - "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." + "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.", + "Module-layout wave2 intentionally retires complete prohibited owning registrations in src/renderer/src/lib/resolved-worktree-execution-host.test.ts. Lost alarms: Both explicit and legacy workspace owners resolve to env-a initially. Replacing the repo catalog refreshes legacy ownership to env-b. A conflicting local repo row makes ownership ambiguous and returns null. Repeated unrelated updates perform zero id reads, an internal work-budget alarm removed. No equivalent replacement coverage or reduced-selector pass is claimed." ], "demotionRule": "Demote or block release if any non-Advanced path mutates Active Server, if local reveal or Add Project depends on the durable default instead of captured workspace/host ownership, if an Add Project operation reaches a different host after it begins, or if transient host state survives restart." }, @@ -8530,13 +8520,13 @@ "providers": ["paired-runtime", "ssh"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": [], - "coverageNotes": "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": "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": "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": "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", @@ -8544,11 +8534,10 @@ "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/parking/output-watchers/parked-terminal-byte-watcher.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/hosted-terminals/streams/remote-runtime-terminal-stall-recovery.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-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/hosted-terminals/streams/remote-runtime-terminal-stall-recovery.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/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", - "pnpm exec vitest run --config config/vitest.config.ts", "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", "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", "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", @@ -8578,7 +8567,6 @@ "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", - "src/renderer/src/components/terminal-pane/parking/output-watchers/parked-terminal-byte-watcher.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", @@ -9023,7 +9011,13 @@ "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.", "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.", "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.", - "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." + "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.", + "Module-layout wave3 intentionally retires complete prohibited owning registrations in src/renderer/src/components/terminal-pane/parking/output-watchers/parked-terminal-byte-watcher.test.ts. Lost alarms: Loss of the OSC title forwarding/order alarm for both pane and tab titles. Loss of the bare Cursor Agent title versus synthetic spinner title/deduplication alarm. Loss of the unread BEL attribution and delayed OS bell notification alarm. Loss of the OSC-terminator BEL exclusion alarm across chunk boundaries. Loss of the working-to-idle prompt-cache and completion-notification alarm. Loss of the same-burst completion-over-bell coalescing alarm. Loss of the resumed-working cancellation of pending completion and cache timer alarm. Loss of the cross-chunk GitHub pull-request discovery and workspace/pane attribution alarm. Loss of the Command Code return-to-done callback wiring alarm; real composer delivery was not established. Loss of the already-in-flight Command Code scrape/return alarm. Loss of the park-time working seed to idle completion alarm. Loss of the no-unobserved-transition completion alarm. Loss of the shutdown cancellation and final-flush attention-suppression alarm. Loss of the sidecar unregistration and pending-bell cancellation alarm. Loss of the same-PTY previous-watcher disposal alarm. Loss of the cold snapshot title restoration without replayed attention alarm. Loss of the stale-derived idle fact state-clear/no-completion alarm. Loss of the fact-consumer disposal and written title-slot clearing alarm. No equivalent replacement coverage or reduced-selector pass is claimed.", + "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.", + "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 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 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 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." ], "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." }, @@ -9202,7 +9196,7 @@ "providers": ["local", "daemon", "ssh", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "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": "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", @@ -9210,7 +9204,7 @@ "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": "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": "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", @@ -9368,7 +9362,12 @@ "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.", "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.", "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.", - "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." + "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.", + "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.", + "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 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 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 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." ], "demotionRule": "Cannot promote without metric artifacts and bounded-byte assertions." }, @@ -9622,7 +9621,7 @@ "oracle": "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.", "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 src/renderer/src/runtime/web-session-tabs-sync/agent-status/paired-reconnect-sidebar-agent-count.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.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-host-surface-replacement.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/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-host-surface-replacement.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-host-surface-replacement.test.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/remote-runtime-pty-transport-create-outcome-recovery.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-handoff.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/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", @@ -9634,7 +9633,6 @@ "testFiles": [ "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts", "src/renderer/src/runtime/web-session-tabs-sync/agent-status/paired-reconnect-sidebar-agent-count.test.ts", - "src/renderer/src/lib/resolved-worktree-execution-host.test.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", @@ -9878,7 +9876,8 @@ "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. Original prospective command before removal: pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.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-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts", "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.", "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.", - "Module-layout wave1 intentionally retires complete prohibited owning registrations in src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-attach-subscription.test.ts. Lost alarms: attaches to an existing remote runtime terminal handle; reports a rejected multiplex write through the pane recovery callback; does not report a rejected write from a superseded multiplex stream; does not report attachment health until the authoritative PTY snapshot arrives; drops its side-effect gauge from the census on %s; recovers when the first restored-terminal subscription attempt is offline; recovers when the runtime closes before a restored subscription becomes ready; surfaces a fatal error during subscription setup exactly once; reports viewer disconnect as an unverifiable remote exit; clears every retained transport error when the current stream becomes healthy. No equivalent replacement coverage or pass for a reduced selector is claimed. All unrelated selectors and historical receipts retain their original scope." + "Module-layout wave1 intentionally retires complete prohibited owning registrations in src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-attach-subscription.test.ts. Lost alarms: attaches to an existing remote runtime terminal handle; reports a rejected multiplex write through the pane recovery callback; does not report a rejected write from a superseded multiplex stream; does not report attachment health until the authoritative PTY snapshot arrives; drops its side-effect gauge from the census on %s; recovers when the first restored-terminal subscription attempt is offline; recovers when the runtime closes before a restored subscription becomes ready; surfaces a fatal error during subscription setup exactly once; reports viewer disconnect as an unverifiable remote exit; clears every retained transport error when the current stream becomes healthy. No equivalent replacement coverage or pass for a reduced selector is claimed. All unrelated selectors and historical receipts retain their original scope.", + "Module-layout wave2 intentionally retires complete prohibited owning registrations in src/renderer/src/lib/resolved-worktree-execution-host.test.ts. Lost alarms: Both explicit and legacy workspace owners resolve to env-a initially. Replacing the repo catalog refreshes legacy ownership to env-b. A conflicting local repo row makes ownership ambiguous and returns null. Repeated unrelated updates perform zero id reads, an internal work-budget alarm removed. No equivalent replacement coverage or reduced-selector pass is claimed." ], "demotionRule": "Cannot promote if provider failure can close panes or if the oracle is screenshot-only." }, @@ -11831,14 +11830,14 @@ "providers": ["local", "daemon", "ssh"], "coveredPlatforms": ["macos"], "coveredProviders": ["local"], - "coverageNotes": "Audit3086: retire the immediate-reply ceiling and thrown renderer-write recovery aliases. Narrow FIFO coverage to deferred preconnect validation and teardown coverage to natural-exit stale ordinary/accepted tails; live acknowledged barriers and disconnect/detach branches are intentionally retired. Prior queue cleanup and unchanged Electron receipts remain exact; no replacement or fresh execution is claimed. Audit1878 retires the dated reduced-source unit receipt. Only the unchanged macOS local Electron receipts remain current, scoped to their exact commands; reduced unit selectors and SSH have no current execution receipt. Historical pre-audit coverageNotes: Deterministic renderer and IPC-transport tests prove count and text ceilings, oldest-reply shedding, explicit query-reply source routing, ordinary-input preservation, acknowledged-write FIFO barriers, single-worker drain reentrancy, one-reply-per-write delivery for OSC, DA1, and CPR replies, real xterm OSC reply generation, drain-failure containment, teardown settlement, and clear/reuse generation fencing. Remote-runtime tests preserve separate query-reply writes across pending input, async validation, and viewport-claim buffering. Host-contract tests prove a later DA1/CPR reply cannot overtake a deferred OSC reply, including a coalesced legacy-client payload. Live macOS Electron tests cover local PTY OSC replies and interactive typing; a macOS-hosted Docker OpenSSH test proves an upstream-node-pty Linux relay keeps OSC/DA1 replies out of the next fish child's stdin. No live daemon, paired-runtime, WSL, physical Linux/Windows client, or binary mixed-version run is registered.", + "coverageNotes": "Audit 3292 retires the empty-queue immediate query-reply delivery example from remote-runtime-pty-query-reply-immediate.test.ts. Pending ordinary-input separation and asynchronous paste-validation ordering cases remain byte-identical, matching the existing assertion reference. The no-pending-input delivery alarm is intentionally lost without equivalent replacement. Existing selectors, unchanged local Electron receipts and historical receipts remain exact; no new runtime, PTY deadline, platform or mixed-version result is claimed. Audit3086: retire the immediate-reply ceiling and thrown renderer-write recovery aliases. Narrow FIFO coverage to deferred preconnect validation and teardown coverage to natural-exit stale ordinary/accepted tails; live acknowledged barriers and disconnect/detach branches are intentionally retired. Prior queue cleanup and unchanged Electron receipts remain exact; no replacement or fresh execution is claimed. Audit1878 retires the dated reduced-source unit receipt. Only the unchanged macOS local Electron receipts remain current, scoped to their exact commands; reduced unit selectors and SSH have no current execution receipt. Historical pre-audit coverageNotes: Deterministic renderer and IPC-transport tests prove count and text ceilings, oldest-reply shedding, explicit query-reply source routing, ordinary-input preservation, acknowledged-write FIFO barriers, single-worker drain reentrancy, one-reply-per-write delivery for OSC, DA1, and CPR replies, real xterm OSC reply generation, drain-failure containment, teardown settlement, and clear/reuse generation fencing. Remote-runtime tests preserve separate query-reply writes across pending input, async validation, and viewport-claim buffering. Host-contract tests prove a later DA1/CPR reply cannot overtake a deferred OSC reply, including a coalesced legacy-client payload. Live macOS Electron tests cover local PTY OSC replies and interactive typing; a macOS-hosted Docker OpenSSH test proves an upstream-node-pty Linux relay keeps OSC/DA1 replies out of the next fish child's stdin. No live daemon, paired-runtime, WSL, physical Linux/Windows client, or binary mixed-version run is registered.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/13137", "https://github.com/stablyai/orca/issues/7329", "https://github.com/stablyai/orca/issues/13892" ], "invariant": "The desktop PTY input queue retains at most 64 explicitly sourced pending terminal query replies and 4096 UTF-16 code units. Every retained reply reaches the provider as one atomic write, and ordinary, acknowledged, and reply input share one invocation-ordered FIFO so no later write overtakes an acknowledged write. Reentrant write callbacks cannot start a second drain worker or strand input admitted after clear/reuse. A reply's own echo is contained on the output side by projecting its known echo shapes; the ESC-initial verbatim shape is matched only when complete, never held as a partial, so a query torn at its own ESC is still answered. Overflow removes only the oldest query replies, never ordinary input except the documented modified-F3/CPR byte collision, and failure or teardown cannot clear a newer queue generation or strand an acknowledged promise.", - "oracle": "Audit3086: retire the immediate-reply ceiling and thrown renderer-write recovery aliases. Narrow FIFO coverage to deferred preconnect validation and teardown coverage to natural-exit stale ordinary/accepted tails; live acknowledged barriers and disconnect/detach branches are intentionally retired. Prior queue cleanup and unchanged Electron receipts remain exact; no replacement or fresh execution is claimed. Audit1878 retires the dated reduced-source unit receipt. Only the unchanged macOS local Electron receipts remain current, scoped to their exact commands; reduced unit selectors and SSH have no current execution receipt. Historical pre-audit oracle: Synchronously enqueue separate 10,000-entry OSC and DA1 reply floods before the scheduled drain and assert that only the initial immediate reply and newest 64 pending replies are written, each as one provider write, before a trailing keystroke. Stall an acknowledged write between earlier and later ordinary/reply input, then require teardown to settle it and same-id reuse to receive no stale tail. Reenter the queue synchronously from an acknowledged write with both enqueue and clear/reuse, requiring one drain and fresh input delivery only after the stale acknowledged write settles false. At the host boundary, defer an OSC reply and assert that separate or legacy-coalesced DA1/CPR replies flush after it in observed query order. At the remote-runtime boundary, preserve separate writes around pending ordinary input, async validation, and viewport-claim buffering. Repeat behind 10,000 ordinary inputs and exercise the text ceiling, real xterm generation, provider-write failure, rejected yield, and clear/reuse generation fencing.", + "oracle": "Audit 3292 retires the empty-queue immediate query-reply delivery example from remote-runtime-pty-query-reply-immediate.test.ts. Pending ordinary-input separation and asynchronous paste-validation ordering cases remain byte-identical, matching the existing assertion reference. The no-pending-input delivery alarm is intentionally lost without equivalent replacement. Existing selectors, unchanged local Electron receipts and historical receipts remain exact; no new runtime, PTY deadline, platform or mixed-version result is claimed. Audit3086: retire the immediate-reply ceiling and thrown renderer-write recovery aliases. Narrow FIFO coverage to deferred preconnect validation and teardown coverage to natural-exit stale ordinary/accepted tails; live acknowledged barriers and disconnect/detach branches are intentionally retired. Prior queue cleanup and unchanged Electron receipts remain exact; no replacement or fresh execution is claimed. Audit1878 retires the dated reduced-source unit receipt. Only the unchanged macOS local Electron receipts remain current, scoped to their exact commands; reduced unit selectors and SSH have no current execution receipt. Historical pre-audit oracle: Synchronously enqueue separate 10,000-entry OSC and DA1 reply floods before the scheduled drain and assert that only the initial immediate reply and newest 64 pending replies are written, each as one provider write, before a trailing keystroke. Stall an acknowledged write between earlier and later ordinary/reply input, then require teardown to settle it and same-id reuse to receive no stale tail. Reenter the queue synchronously from an acknowledged write with both enqueue and clear/reuse, requiring one drain and fresh input delivery only after the stale acknowledged write settles false. At the host boundary, defer an OSC reply and assert that separate or legacy-coalesced DA1/CPR replies flush after it in observed query order. At the remote-runtime boundary, preserve separate writes around pending ordinary input, async validation, and viewport-claim buffering. Repeat behind 10,000 ordinary inputs and exercise the text ceiling, real xterm generation, provider-write failure, rejected yield, and clear/reuse generation fencing.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts src/shared/terminal/protocol/queries/terminal-query-reply.test.ts src/shared/terminal/pty/ingress/pty-startup-ingress-live-query-reply.test.ts src/shared/terminal/pty/ingress/pty-startup-reply-echo-shapes.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/output/remote-runtime-pty-batching.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-query-reply-immediate.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-input-coalescing.test.ts", @@ -11969,7 +11968,8 @@ "Reply overload intentionally sheds the oldest synthetic replies; the modified-F3/CPR byte collision shares that budget, and live application behavior under a pathological query flood is not measured.", "Audit1878 retires this complete dated receipt because a source in its selector was reduced. It does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-08-30\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-input-write-queue.test.ts src/renderer/src/components/terminal-pane/pty-transport-input-write.test.ts src/shared/terminal-query-reply.test.ts src/shared/pty-startup-ingress-live-query-reply.test.ts src/shared/pty-startup-reply-echo-shapes.test.ts\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts src/shared/terminal/protocol/queries/terminal-query-reply.test.ts src/shared/terminal/pty/ingress/pty-startup-ingress-live-query-reply.test.ts src/shared/terminal/pty/ingress/pty-startup-reply-echo-shapes.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 15,\n \"summary\": \"Five files and 149 tests passed in 15.16 seconds, including explicit IPC reply-source routing, the 10,000-reply count and text ceilings, 10,000-entry ordinary backlog preservation, acknowledged-write FIFO barriers, synchronous reentrancy fencing, prompt teardown settlement, same-id generation fencing, real xterm OSC query floods, single-shot drain-failure recovery, and one-reply-per-write echo containment.\"\n }", "Audit1878 removes standalone reply-classifier inventory, ordinary-keystroke helper/no-write checks and a latency-order title that never executes the host path from pty-startup-ingress-live-query-reply.test.ts. It also removes projection needle/refusal/holdPartial and ConPTY/WSL string/array inventories from pty-startup-reply-echo-shapes.test.ts, including the direct short-needle and ESC-hold guard alarms. Captured echo matching and actual ingress writes/output state remain, without equivalent replacement coverage. Only the two unchanged macOS local Electron receipts remain active; neither proves the reduced five-file unit selector, SSH, a new soak result, or a new measured budget.", - "Audit3086: retire the immediate-reply ceiling and thrown renderer-write recovery aliases. Narrow FIFO coverage to deferred preconnect validation and teardown coverage to natural-exit stale ordinary/accepted tails; live acknowledged barriers and disconnect/detach branches are intentionally retired. Prior queue cleanup and unchanged Electron receipts remain exact; no replacement or fresh execution is claimed." + "Audit3086: retire the immediate-reply ceiling and thrown renderer-write recovery aliases. Narrow FIFO coverage to deferred preconnect validation and teardown coverage to natural-exit stale ordinary/accepted tails; live acknowledged barriers and disconnect/detach branches are intentionally retired. Prior queue cleanup and unchanged Electron receipts remain exact; no replacement or fresh execution is claimed.", + "Audit 3292 retires the empty-queue immediate query-reply delivery example from remote-runtime-pty-query-reply-immediate.test.ts. Pending ordinary-input separation and asynchronous paste-validation ordering cases remain byte-identical, matching the existing assertion reference. The no-pending-input delivery alarm is intentionally lost without equivalent replacement. Existing selectors, unchanged local Electron receipts and historical receipts remain exact; no new runtime, PTY deadline, platform or mixed-version result is claimed." ], "demotionRule": "Keep experimental or revert if ordinary input is evicted, pending replies exceed either ceiling, retained replies are coalesced, a trailing key sits behind more than the bounded reply window, or the gate develops unexplained flakes." }, @@ -12736,14 +12736,14 @@ "providers": ["local", "remote-runtime", "ssh"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": ["local", "remote-runtime", "ssh"], - "coverageNotes": "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": "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": "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": "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/watcher-process/parcel-watcher-unsubscribe-timeout.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/watchers/filesystem-watcher-native-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts src/main/ipc/filesystem/watcher-process/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", @@ -13177,7 +13177,12 @@ "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.", "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.", "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.", - "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." + "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.", + "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.", + "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 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 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 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." ], "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." }, @@ -14422,10 +14427,10 @@ "providers": ["paired-runtime"], "coveredPlatforms": ["linux"], "coveredProviders": ["paired-runtime"], - "coverageNotes": "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": "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": "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": "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", @@ -14507,7 +14512,12 @@ "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.", "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.", "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.", - "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." + "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.", + "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.", + "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 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 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 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." ], "demotionRule": "Keep experimental if any direction skips or fails; do not extend timeouts or retry to green." }, diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 9ed17e62079..0c336f13bd1 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -4620,7 +4620,6 @@ "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/renderer/src/app-shell/app-command-handlers-tab-rename.test.ts": 1786, "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, @@ -4775,7 +4774,6 @@ "src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx": 3251, "src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx": 4357, "src/renderer/src/components/browser-pane/workspace-doc/doc-preview-artifact-share.test.ts": 1754, - "src/renderer/src/components/browser-pane/workspace-doc/doc-preview-document-actions.test.ts": 327, "src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts": 1057, "src/renderer/src/components/browser-pane/workspace-doc/doc-preview-webview-attach.test.ts": 200, "src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts": 439, @@ -4836,7 +4834,6 @@ "src/renderer/src/components/editor/EditorFileLocationMenuItems.test.tsx": 846, "src/renderer/src/components/editor/EditorPanel.custom-editor-flush.test.tsx": 2478, "src/renderer/src/components/editor/EditorPanel.diff-rich-owner.test.tsx": 2823, - "src/renderer/src/components/editor/EditorPanelHeaderPath.test.tsx": 2664, "src/renderer/src/components/editor/notebook/cells/IpynbCellEditor.external-sync.test.tsx": 1660, "src/renderer/src/components/editor/notebook/kernel/IpynbKernelToolbar.test.tsx": 736, "src/renderer/src/components/editor/notebook/document/IpynbRendering.test.tsx": 2143, @@ -5102,7 +5099,6 @@ "src/renderer/src/components/mobile/WindowsFirewallNotice.test.tsx": 691, "src/renderer/src/components/mobile/paired-mobile-devices.test.ts": 192, "src/renderer/src/components/mobile/use-mobile-page-paired-devices.test.ts": 475, - "src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-bulk-progress.test.tsx": 3261, "src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-failed-chat-watch.test.ts": 1954, "src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-finished-run.test.tsx": 4173, "src/renderer/src/components/native-chat/messages/rows/NativeChatAgentMessageCard.test.tsx": 3700, @@ -5124,27 +5120,15 @@ "src/renderer/src/components/native-chat/media/visuals/NativeChatMarkdown.visual.test.tsx": 2860, "src/renderer/src/components/native-chat/messages/reasoning/NativeChatMessageList.live-reasoning.test.tsx": 20337, "src/renderer/src/components/native-chat/NativeChatMessageList.new-rows-marker.test.tsx": 4304, - "src/renderer/src/components/native-chat/viewport/history/NativeChatMessageList.older-history.test.tsx": 12659, - "src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.opening-send.test.tsx": 3604, - "src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.queued-turn-order.test.tsx": 2949, - "src/renderer/src/components/native-chat/viewport/navigation/NativeChatMessageList.rail-history-jump.test.tsx": 23851, "src/renderer/src/components/native-chat/viewport/scroll/NativeChatMessageList.scroll-behavior.test.tsx": 14260, - "src/renderer/src/components/native-chat/subagents/NativeChatMessageList.subagent-sections.test.tsx": 7517, - "src/renderer/src/components/native-chat/surfaces/integration/NativeChatMessageList.test.tsx": 4252, - "src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-indicator.test.tsx": 4070, - "src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.turn-membership.test.tsx": 3527, - "src/renderer/src/components/native-chat/session/structured/delivery/NativeChatMessageList.unsent-message.test.tsx": 3069, "src/renderer/src/components/native-chat/viewport/scroll/NativeChatMessageList.visual-scroll.test.tsx": 6691, - "src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing.test.tsx": 20958, "src/renderer/src/components/native-chat/viewport/rail/NativeChatMessageRail.test.tsx": 1134, - "src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.test.tsx": 3533, "src/renderer/src/components/native-chat/NativeChatNewRowsMarker.test.tsx": 3019, "src/renderer/src/components/native-chat/usage/NativeChatNoticeRow.test.tsx": 3399, "src/renderer/src/components/native-chat/pane/actions/NativeChatPaneHeader.test.tsx": 2736, "src/renderer/src/components/native-chat/composer/editor/NativeChatPromptEditor.paragraph-selection.test.tsx": 652, "src/renderer/src/components/native-chat/composer/editor/NativeChatPromptEditor.test.tsx": 1110, "src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.test.tsx": 762, - "src/renderer/src/components/native-chat/queue/NativeChatQueuedMessageList.in-flight.test.tsx": 1865, "src/renderer/src/components/native-chat/queue/NativeChatQueuedMessageRows.test.tsx": 2691, "src/renderer/src/components/native-chat/prompts/NativeChatResolutionReceipt.test.tsx": 912, "src/renderer/src/components/native-chat/media/images/NativeChatResolvedView.context-menu.test.tsx": 4025, @@ -5201,7 +5185,6 @@ "src/renderer/src/components/native-chat/drafts/native-chat-draft-retention.test.ts": 1415, "src/renderer/src/components/native-chat/attachments/intake/native-chat-external-attachments-destination.test.tsx": 951, "src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.test.ts": 1937, - "src/renderer/src/components/native-chat/pane/actions/native-chat-header-ownership.test.tsx": 2796, "src/renderer/src/components/native-chat/links/actions/native-chat-host-file-open.test.ts": 895, "src/renderer/src/components/native-chat/links/previews/native-chat-hover-preview-cache.test.ts": 49, "src/renderer/src/components/native-chat/attachments/chips/native-chat-image-references.test.tsx": 2485, @@ -5245,8 +5228,6 @@ "src/renderer/src/components/native-chat/viewport/rail/structured-agent-session-rail-outline.test.ts": 48, "src/renderer/src/components/native-chat/session/structured/read/structured-agent-session-read-transport.test.ts": 243, "src/renderer/src/components/native-chat/session/status/structured-agent-session-status-bridge-clock.test.tsx": 2070, - "src/renderer/src/components/native-chat/session/status/structured-agent-session-status-bridge-failed-start.test.tsx": 2398, - "src/renderer/src/components/native-chat/session/status/structured-agent-session-status-bridge-unconfirmed-start.test.tsx": 2328, "src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-transcript-order.test.ts": 294, "src/renderer/src/components/native-chat/session/attention/structured-attention-dispatch.test.ts": 1974, "src/renderer/src/components/native-chat/session/status/structured-chat-sleep-startup.test.tsx": 2285, @@ -5309,7 +5290,6 @@ "src/renderer/src/components/new-workspace/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/onboarding/onboarding-feature-setup.test.ts": 76, "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, @@ -5400,7 +5380,6 @@ "src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-watch-reconcile.test.ts": 1906, "src/renderer/src/components/right-sidebar/folder-workspace-attached-worktrees.test.ts": 70, "src/renderer/src/components/right-sidebar/source-control/sync/git-status-refresh.test.ts": 553, - "src/renderer/src/components/right-sidebar/source-control/sync/git-status-twin-copy.test.ts": 1841, "src/renderer/src/components/right-sidebar/hosted-review/folder-checks/parent-pr-checks-rows.test.ts": 374, "src/renderer/src/components/plugins/frames/plugin-frame-host-declarative.test.ts": 439, "src/renderer/src/components/right-sidebar/plugin-panels/health/plugin-panel-act-driver.test.ts": 293, @@ -5470,7 +5449,6 @@ "src/renderer/src/components/settings/repository/worktrees/SparsePresetSettingsSection.test.tsx": 744, "src/renderer/src/components/settings/ssh/server-actions/SshHostDeltaMoveDialog.test.tsx": 438, "src/renderer/src/components/settings/ssh/server-actions/SshHostRecoverServerAction.test.tsx": 669, - "src/renderer/src/components/settings/ssh/SshPane.test.tsx": 1699, "src/renderer/src/components/settings/ssh/targets/SshTargetForm.test.tsx": 1014, "src/renderer/src/components/settings/ssh/targets/SshTargetList.test.tsx": 2093, "src/renderer/src/components/settings/tasks/TaskSourceSimpleSetup.test.tsx": 527, @@ -5573,7 +5551,6 @@ "src/renderer/src/components/sidebar/workspace-board/surface/use-workspace-kanban-drawer-lingering.test.tsx": 262, "src/renderer/src/components/sidebar/workspace-board/selection/use-workspace-kanban-selection.test.tsx": 243, "src/renderer/src/components/sidebar/workspace-card/review/use-workspace-reference-details.test.tsx": 1335, - "src/renderer/src/components/sidebar/worktree-list/navigation/use-workspace-reveal-body-redirect.test.tsx": 215, "src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.test.tsx": 565, "src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-agent-rows-subscriptions.test.tsx": 3635, "src/renderer/src/components/sidebar/host-admission/wsl/use-wsl-distro-list.test.ts": 542, @@ -5625,7 +5602,6 @@ "src/renderer/src/components/sidebar/worktree-list/listing/worktree-sort-label-ordering.test.ts": 114, "src/renderer/src/components/sidebar/wsl-host-offer-move.test.ts": 227, - "src/renderer/src/components/skills/installation/SkillInstallManagementDialog.test.tsx": 3300, "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, @@ -5635,7 +5611,6 @@ "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/SshStatusSegment.large-host-list.test.tsx": 1838, "src/renderer/src/components/status-bar/StatusBarUsageChangeNotices.test.tsx": 785, "src/renderer/src/components/status-bar/UpdateStatusSegment.test.tsx": 2484, "src/renderer/src/components/status-bar/account-switch-row-keyboard.test.tsx": 2286, @@ -5662,14 +5637,12 @@ "src/renderer/src/components/tab-bar/TabStripScrollIndicator.test.tsx": 356, "src/renderer/src/components/tab-bar/cli-chat-resume-close-terminal.test.ts": 598, "src/renderer/src/components/tab-bar/cli-chat-resume-run-close.test.ts": 3079, - "src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts": 3848, "src/renderer/src/components/tab-bar/group-tab-order.test.ts": 2091, "src/renderer/src/components/tab-bar/host-agent-launch-preferences-source.test.tsx": 3154, "src/renderer/src/components/tab-bar/recent-tab-switching.test.ts": 1795, "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-bar-layout-owner-props.test.ts": 174, - "src/renderer/src/components/tab-bar/tab-bar-quick-commands-shortcut.test.tsx": 273, "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, @@ -5772,7 +5745,6 @@ "src/renderer/src/components/terminal-pane/pty-connection/agent-identity/foreground-process/pane-foreground-inspect-observation-identity.test.ts": 226, "src/renderer/src/components/terminal-pane/pty-connection/agent-identity/foreground-process/pane-foreground-process-exit-retire.test.ts": 329, "src/renderer/src/components/sidebar/workspace-card/activity/structured-chat-activity-status-live.test.tsx": 4146, - "src/renderer/src/components/terminal-pane/parking/output-watchers/parked-terminal-byte-watcher.test.ts": 2837, "src/renderer/src/components/terminal-pane/parking/output-watchers/parked-terminal-command-status.test.ts": 352, "src/renderer/src/components/terminal-pane/layout/close/pending-pane-close-confirmation.test.ts": 4695, "src/renderer/src/components/terminal-pane/layout/close/pending-runtime-pane-close.test.ts": 3487, @@ -5862,7 +5834,6 @@ "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts": 1311, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-handoff.test.ts": 14353, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-outcome-recovery.test.ts": 2041, - "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-empty-initial-snapshot.test.ts": 1491, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-end-verdict.test.ts": 942, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts": 1763, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-healthy-link-reattach.test.ts": 1595, @@ -5879,7 +5850,6 @@ "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-pending-host-surface-attach.test.ts": 1768, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-prebind-discard-notice.test.ts": 889, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-reattach-type-ahead.test.ts": 3894, - "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-reveal-round-trips.test.ts": 1023, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-snapshot-replay.test.ts": 1717, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-spawn-intent.test.ts": 2215, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-split-leaf-activation.test.ts": 2034, @@ -5990,7 +5960,6 @@ "src/renderer/src/components/terminal-pane/viewport/visibility/use-terminal-pane-global-effects-visibility-resume.test.ts": 1951, "src/renderer/src/components/terminal-pane/viewport/visibility/use-terminal-pane-global-effects-window-focus-recovery.test.ts": 1836, "src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts": 1806, - "src/renderer/src/components/terminal-pane/viewport/visibility/use-terminal-scroll-visibility-memory.test.ts": 79, "src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts": 752, "src/renderer/src/components/terminal-pane/viewport/visibility/use-terminal-window-wake-recovery.test.ts": 494, "src/renderer/src/components/terminal-pane/links/http/wrapped-terminal-http-link-limits.test.ts": 108, @@ -6006,7 +5975,6 @@ "src/renderer/src/components/terminal/active-terminal-repair-loop.react185.test.tsx": 1998, "src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts": 1707, "src/renderer/src/components/terminal/background-terminal-worktree-visibility.test.ts": 1790, - "src/renderer/src/components/terminal/initial-terminal-admission-wait.test.tsx": 2444, "src/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsx": 786, "src/renderer/src/components/terminal/running-terminal-close-guard.test.ts": 99, "src/renderer/src/components/terminal/startup-terminal-tab-hold.test.ts": 2118, @@ -6030,7 +5998,6 @@ "src/renderer/src/components/use-quick-open-interaction.test.tsx": 1987, "src/renderer/src/components/use-task-creation-draft-retention.test.ts": 3185, "src/renderer/src/components/use-terminal-bulk-close-actions.frame-flush.test.tsx": 2300, - "src/renderer/src/components/use-terminal-create-actions.test.tsx": 302, "src/renderer/src/components/use-terminal-editor-close-foundation.window-close.test.tsx": 2105, "src/renderer/src/components/use-terminal-parking-pass.test.tsx": 2142, "src/renderer/src/components/use-terminal-window-lifecycle.frame-flush.test.tsx": 2164, @@ -6053,9 +6020,7 @@ "src/renderer/src/components/workspace-emoji/WorkspaceEmojiPickerPanel.test.tsx": 763, "src/renderer/src/components/workspace-emoji/useWorkspaceEmojiShortcodeInput.test.tsx": 365, "src/renderer/src/components/worktree-creation/PendingNativeChatCreation.test.tsx": 4075, - "src/renderer/src/components/worktree-jump/WorktreeJumpPalette.linear-url.test.tsx": 3372, "src/renderer/src/components/worktree-jump/WorktreeJumpPalette.recent-tabs.behavior.test.tsx": 4445, - "src/renderer/src/components/worktree-jump/WorktreeJumpPalette.recent-tabs.test.tsx": 9384, "src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx": 4442, "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, @@ -6161,7 +6126,6 @@ "src/renderer/src/hooks/useIpcEvents-client-hosted-browser-rows.test.ts": 1894, "src/renderer/src/hooks/useIpcEvents-close-routing-active-browser-tab.test.ts": 4572, "src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts": 5812, - "src/renderer/src/hooks/useIpcEvents-cmd-j-digit-chord.test.ts": 2703, "src/renderer/src/hooks/useIpcEvents-lifecycle.test.ts": 2326, "src/renderer/src/hooks/useIpcEvents-new-workspace-shortcut.test.ts": 72, "src/renderer/src/hooks/useIpcEvents-runtime-environment-selectors.test.ts": 530, @@ -6179,7 +6143,6 @@ "src/renderer/src/hooks/useReadOnScreenAttention.test.ts": 1915, "src/renderer/src/hooks/useRetiredWorktreeNames.test.ts": 593, - "src/renderer/src/hooks/useUnreadDockBadge.test.ts": 2126, "src/renderer/src/hooks/virtualized-hidden-row-measurement.test.ts": 199, "src/renderer/src/hooks/worktree-change-refresh-queue.test.ts": 59, "src/renderer/src/i18n/I18nProvider.test.tsx": 2101, @@ -6189,12 +6152,11 @@ "src/renderer/src/i18n/plugin-pack-plurals.test.ts": 191, "src/renderer/src/i18n/relative-time-format.test.ts": 53, "src/renderer/src/i18n/ui-intl-formatters.test.ts": 208, - "src/renderer/src/lib/activate-ai-vault-structured-session-host.test.ts": 589, - "src/renderer/src/lib/activate-ai-vault-structured-session-reveal.test.ts": 2099, + "src/renderer/src/lib/agent-session/open/activate-ai-vault-structured-session-reveal.test.ts": 2099, "src/renderer/src/lib/workspace/tabs/activate-tab-and-focus-pane.test.ts": 54, "src/renderer/src/lib/agent-session/messaging/terminal/active-agent-note-send-explicit-target.test.ts": 980, "src/renderer/src/lib/agent-session/messaging/terminal/active-agent-note-send-focused-session.test.ts": 536, - "src/renderer/src/lib/activity-thread-display.test.ts": 134, + "src/renderer/src/lib/workspace/activity/activity-thread-display.test.ts": 134, "src/renderer/src/lib/agent-account-restart-startup.test.ts": 1780, "src/renderer/src/lib/agent-session/launch/background/agent-background-session-launch-host.test.ts": 1910, "src/renderer/src/lib/agent-draft-readiness.test.ts": 245, @@ -6204,7 +6166,6 @@ "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-runtime-liveness-race.test.ts": 1914, "src/renderer/src/lib/agent-session/launch/pane/agent-launch-pane-verdict-application.test.ts": 1869, "src/renderer/src/lib/agent-session/launch/routing/agent-launch-route-input.test.ts": 1659, - "src/renderer/src/lib/agent-session/launch/routing/agent-launch-route-registered-agents.test.ts": 1749, "src/renderer/src/lib/agent-session/launch/pane/agent-launch-tab-main-written.test.ts": 2084, "src/renderer/src/lib/agent-session/launch/pane/agent-launch-tab-publication.test.ts": 1855, "src/renderer/src/lib/agent-session/launch/pane/agent-launch-through-host.test.ts": 1975, @@ -6213,7 +6174,6 @@ "src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts": 445, "src/renderer/src/lib/agent-session/resume/agent-resume-launch-target.test.ts": 3911, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-after-failure.test.ts": 870, - "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-close-race.test.ts": 983, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-create-message.test.ts": 2521, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-different-request.test.ts": 885, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-exited-owner.test.ts": 1289, @@ -6224,9 +6184,6 @@ "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-prompt.test.ts": 710, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-record.test.ts": 151, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-resume-identity.test.ts": 828, - "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-unconfirmed-or-retried.test.ts": 1085, - "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch.test.ts": 977, - "src/renderer/src/lib/agent-session/launch/structured-agent-session-new-chat-own-launch.test.ts": 2177, "src/renderer/src/lib/agent-session/structured-agent-session-draft-position-lifetime.test.tsx": 3166, "src/renderer/src/lib/agent-session/structured-agent-session-ordinary-draft.test.tsx": 9907, "src/renderer/src/lib/agent-session/structured-agent-session-provisional-tab.test.ts": 3672, @@ -6250,7 +6207,6 @@ "src/renderer/src/lib/bounded-generation-map.test.ts": 35, "src/renderer/src/lib/browser/history/browser-history-match.test.ts": 328, "src/renderer/src/lib/browser/navigation/browser-link-destination.test.ts": 1839, - "src/renderer/src/lib/browser/navigation/browser-link-open-layout-owner.test.ts": 3133, "src/renderer/src/lib/browser/navigation/browser-link-open.test.ts": 2215, "src/renderer/src/lib/browser/navigation/browser-link-profile-isolation.test.ts": 2511, "src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts": 1983, @@ -6261,21 +6217,19 @@ "src/renderer/src/lib/claude-account-switch-sessions.test.ts": 782, "src/renderer/src/lib/claude-session-account-move.test.ts": 1816, "src/renderer/src/lib/clipboard/images/clipboard-image-copy.test.ts": 243, - "src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts": 526, - "src/renderer/src/lib/cmd-j-linear-issue-intent.test.ts": 42, + "src/renderer/src/lib/workspace/search/palette/cmd-j-host-qualified-candidate-ownership.test.ts": 526, + "src/renderer/src/lib/workspace/search/palette/cmd-j-linear-issue-intent.test.ts": 42, "src/renderer/src/lib/code-host-error-copy.test.ts": 297, - "src/renderer/src/lib/codex-pane-selection-lane.test.ts": 543, + "src/renderer/src/lib/agent-session/accounts/codex-pane-selection-lane.test.ts": 543, "src/renderer/src/lib/agent-session/accounts/codex/codex-session-restart-shell-flap.test.ts": 1745, "src/renderer/src/lib/agent-session/accounts/codex/codex-session-restart.test.ts": 2039, - "src/renderer/src/lib/codex-stale-pane-account-identity.test.ts": 1823, - "src/renderer/src/lib/codex-stale-pane-sweep.test.ts": 1817, + "src/renderer/src/lib/agent-session/accounts/codex/codex-stale-pane-account-identity.test.ts": 1823, + "src/renderer/src/lib/agent-session/accounts/codex/codex-stale-pane-sweep.test.ts": 1817, "src/renderer/src/lib/source-control/review/comments/comment-body-submit-state.test.ts": 55, "src/renderer/src/lib/composer-submit-cancellation.test.ts": 41, "src/renderer/src/lib/workspace/ownership/connection-context.test.ts": 1817, "src/renderer/src/lib/create-untitled-markdown.test.ts": 566, - "src/renderer/src/lib/desktop-created-server-tabs.test.ts": 1933, "src/renderer/src/lib/workspace/ownership/direct-ssh-target-scope.test.ts": 48, - "src/renderer/src/lib/workspace/creation/work-item/direct-work-item-setup-callers.test.tsx": 2436, "src/renderer/src/lib/workspace/creation/work-item/direct-work-item-setup.test.ts": 2072, "src/renderer/src/lib/browser/documents/doc-preview-grants.test.ts": 2094, "src/renderer/src/lib/editor/file-operations/editor-file-operation-owner.test.ts": 2848, @@ -6285,13 +6239,9 @@ "src/renderer/src/runtime/hosts/platform/execution-host-facts.test.ts": 1796, "src/renderer/src/components/sidebar/sidebar-feedback/feedback-image-attachments.test.ts": 557, "src/renderer/src/lib/files/search/file-search-selection.test.ts": 51, - "src/renderer/src/lib/finished-agent-resume-resurrection.test.ts": 1872, + "src/renderer/src/lib/agent-session/resume/finished-agent-resume-resurrection.test.ts": 1872, "src/renderer/src/components/terminal-pane/parking/retention/foreground-terminal-tabs.test.ts": 55, "src/renderer/src/lib/work-items/github/github-source-runtime-context.test.ts": 62, - "src/renderer/src/lib/host-mirror-handle-gap-drain.test.ts": 1706, - "src/renderer/src/lib/host-mirror-handle-gap-resume.test.ts": 1811, - "src/renderer/src/lib/host-mirrored-pane-resume-replay.test.ts": 1814, - "src/renderer/src/lib/browser/navigation/http-link-completion.test.ts": 1760, "src/renderer/src/lib/browser/navigation/http-link-routing-store.test.ts": 2211, "src/renderer/src/lib/text-input/ime/ime-composition-keyboard-event.test.ts": 274, "src/renderer/src/lib/text-input/ime/ime-text-field.test.tsx": 739, @@ -6312,7 +6262,6 @@ "src/renderer/src/app-shell/startup/lazy-with-retry.never-landed-reload.test.ts": 194, "src/renderer/src/lib/work-items/linear/linear-board-drag-payload.test.ts": 58, "src/renderer/src/lib/work-items/linear/linear-issue-workspace-attachment.test.ts": 99, - "src/renderer/src/lib/link-source-local-open-owner.test.ts": 433, "src/renderer/src/lib/work-items/linked-work-item-context.test.ts": 64, "src/renderer/src/lib/editor/monaco/monaco-editor-gutter-disposal.test.ts": 295, "src/renderer/src/lib/monaco-languages/markdown-heading-outline.test.ts": 70, @@ -6329,11 +6278,10 @@ "src/renderer/src/lib/monaco-languages/textmate-token-provider.test.ts": 245, "src/renderer/src/lib/monaco-languages/zig-highlighting.test.ts": 7984, "src/renderer/src/lib/agent-session/resume/cli-fork/native-chat-cli-fork-preparation.test.ts": 2773, - "src/renderer/src/lib/open-agent-message-sender.test.ts": 1497, "src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts": 545, - "src/renderer/src/lib/order-empty-query-worktrees.test.ts": 62, + "src/renderer/src/lib/workspace/search/palette/order-empty-query-worktrees.test.ts": 62, "src/renderer/src/lib/files/drop/os-file-drop-cancellation-guard.test.ts": 204, - "src/renderer/src/lib/paired-runtime-closed-tab-resume.test.ts": 2008, + "src/renderer/src/lib/agent-session/resume/paired-runtime-closed-tab-resume.test.ts": 2008, "src/renderer/src/lib/pane-manager/pane-close-focus-successor.test.ts": 1123, "src/renderer/src/lib/pane-manager/pane-container-listener-lifecycle.test.ts": 312, "src/renderer/src/lib/pane-manager/pane-cursor-blink-suspension.test.ts": 429, @@ -6386,8 +6334,7 @@ "src/renderer/src/lib/text-input/paste/paste-payload-metadata.test.ts": 53, "src/renderer/src/lib/path-display/path-head-elision.test.ts": 53, "src/renderer/src/lib/path.test.ts": 55, - "src/renderer/src/lib/plugin-command-keybindings.test.ts": 1909, - "src/renderer/src/lib/plugin-command-replacements.test.ts": 95, + "src/renderer/src/lib/plugins/commands/plugin-command-keybindings.test.ts": 1909, "src/renderer/src/lib/plugin-icons/plugin-icon-svg.test.ts": 231, "src/renderer/src/lib/editor/appearance/plugin-monaco-token-rules.test.ts": 51, "src/renderer/src/lib/source-control/review/pr-bot-author-overrides.test.ts": 349, @@ -6396,13 +6343,8 @@ "src/renderer/src/lib/workspace/creation/project-host-workspace-target.jira-mapping.test.ts": 76, "src/renderer/src/lib/workspace/creation/project-host-workspace-target.test.ts": 92, "src/renderer/src/lib/editor/file-operations/remap-open-editor-tabs-for-path-change.test.ts": 2178, - "src/renderer/src/lib/rename-user-named-tab-access.test.ts": 2804, "src/renderer/src/lib/renderer-agent-status-observation-ingress.test.ts": 81, "src/renderer/src/diagnostics/memory/renderer-memory-profile.test.ts": 70, - "src/renderer/src/lib/repo-search.test.ts": 54, - "src/renderer/src/lib/repo-slug-cache.test.ts": 52, - "src/renderer/src/lib/repo-slug-index.test.ts": 2240, - "src/renderer/src/lib/resolved-worktree-execution-host.test.ts": 300, "src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session-deferred-pane.test.ts": 1747, "src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session-direct-ssh-hydration-gap.test.ts": 1654, "src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session-execution-host-scope.test.ts": 1924, @@ -6414,15 +6356,10 @@ "src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session-suppress-navigation.test.ts": 1919, "src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session.test.ts": 2140, "src/renderer/src/lib/resume-stale-structured-agent-session.test.ts": 1774, - "src/renderer/src/lib/retracted-host-pane-resume.test.ts": 2009, + "src/renderer/src/lib/agent-session/resume/retracted-host-pane-resume.test.ts": 2009, "src/renderer/src/lib/review-owner.test.ts": 238, - "src/renderer/src/lib/run-quick-command-in-new-tab.test.ts": 82, "src/renderer/src/lib/runtime-host-copy.test.ts": 317, - "src/renderer/src/lib/script-textarea-rows.test.ts": 93, - "src/renderer/src/lib/session-write-subscriber-acknowledgment.test.ts": 1823, - "src/renderer/src/lib/session-write-subscriber.test.ts": 1882, - "src/renderer/src/lib/sidebar-ended-creations.test.ts": 1889, - "src/renderer/src/lib/sidebar-pending-layer.test.ts": 338, + "src/renderer/src/components/sidebar/sidebar-feed/sidebar-pending-layer.test.ts": 338, "src/renderer/src/lib/sidebar-shadow/workspace-activity-shadow.test.ts": 1728, "src/renderer/src/lib/simulator/launch/simulator-launch-coordination.test.ts": 43, "src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts": 515, @@ -6430,32 +6367,25 @@ "src/renderer/src/lib/simulator/tabs/simulator-tab-layout-owner.test.ts": 2398, "src/renderer/src/lib/simulator/tabs/simulator-tab-palette-activation.test.ts": 1903, "src/renderer/src/lib/source-control/remote/source-control-remote-error.test.ts": 340, - "src/renderer/src/lib/ssh-config-passive-sync.test.ts": 1513, + "src/renderer/src/runtime/hosts/ssh/ssh-config-passive-sync.test.ts": 1513, "src/renderer/src/diagnostics/memory/state-collection-byte-estimate.test.ts": 86, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-draft.test.ts": 1042, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-prerequisites.test.ts": 2427, - "src/renderer/src/lib/agent-session/options/structured-agent-session-selection-lifetime.test.tsx": 2947, - "src/renderer/src/lib/structured-chat-tab-index.test.ts": 45, - "src/renderer/src/lib/structured-session-open-consumers.test.tsx": 2643, "src/renderer/src/lib/syntax-highlighting/incremental-syntax-tokenizer.test.ts": 665, "src/renderer/src/lib/syntax-highlighting/syntax-highlight-scheduler.test.ts": 149, "src/renderer/src/lib/syntax-highlighting/syntax-highlighter.test.ts": 539, "src/renderer/src/lib/syntax-highlighting/textmate-core.test.ts": 60, - "src/renderer/src/lib/tab-agent-status-index.test.ts": 210, "src/renderer/src/lib/task-provider-error-copy.test.ts": 363, "src/renderer/src/app-shell/appearance/terminal-app-theme.test.ts": 301, - "src/renderer/src/lib/terminal-input-activity-coalescing.test.ts": 43, "src/renderer/src/lib/text-input/paste/text-control-paste-ownership.test.ts": 217, "src/renderer/src/lib/text-input/paste/text-control-paste.test.ts": 222, "src/renderer/src/lib/text-generation-error-copy.test.ts": 466, "src/renderer/src/lib/typing-latency/echo-instrumentation.test.ts": 145, "src/renderer/src/lib/typing-latency/renderer-long-tasks.test.ts": 75, "src/renderer/src/lib/typing-latency/sample-window.test.ts": 77, - "src/renderer/src/lib/unread-badge-count-selector.test.ts": 1930, - "src/renderer/src/lib/use-tab-agent-observed-signal-dispatch.test.tsx": 1971, - "src/renderer/src/lib/use-tab-agent-opencode-native-title.test.ts": 2093, - "src/renderer/src/lib/use-tab-agent.test.ts": 1961, - "src/renderer/src/lib/wake-sleeping-agents-live-unmounted-pane.test.ts": 2432, + "src/renderer/src/attention/unread/unread-badge-count-selector.test.ts": 1930, + "src/renderer/src/lib/agent-session/tab-identity/use-tab-agent-observed-signal-dispatch.test.tsx": 1971, + "src/renderer/src/lib/agent-session/tab-identity/use-tab-agent.test.ts": 1961, "src/renderer/src/runtime/hosts/capabilities/windows-terminal-capabilities-race.test.ts": 450, "src/renderer/src/lib/workspace/activation/workspace-activation-path-gate.test.ts": 2107, "src/renderer/src/lib/browser/workspace/workspace-browser-tab-open-placement.test.ts": 1996, @@ -6489,8 +6419,7 @@ "src/renderer/src/lib/workspace/activation/worktree-reactivation-tab-forkbomb.test.ts": 4131, "src/renderer/src/lib/workspace/ownership/worktree-runtime-owner-index.detected.test.ts": 121, "src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts": 380, - "src/renderer/src/lib/worktree-status-spinner-launch-agent.test.ts": 271, - "src/renderer/src/lib/worktree-status.test.ts": 306, + "src/renderer/src/lib/workspace/activity/worktree-status.test.ts": 306, "src/renderer/src/lib/workspace/persistence/wsl-move-renderer-store-rewrites.test.ts": 1072, "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, @@ -6512,7 +6441,6 @@ "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/agent-status/remote-agent-row-last-assistant-message.test.ts": 1776, - "src/renderer/src/runtime/files/mutations/remote-host-file-delete-repro.test.ts": 1890, "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, @@ -6544,14 +6472,12 @@ "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-held-tabs.test.ts": 2302, "src/renderer/src/runtime/workspace-layout/server/server-layout-frames.test.ts": 2053, "src/renderer/src/runtime/native-chat/status/structured-agent-session-status-feed-lifecycle.test.ts": 62, "src/renderer/src/runtime/native-chat/status/structured-agent-session-status-feed.test.ts": 82, "src/renderer/src/runtime/native-chat/status/structured-agent-session-turn-completion-feed.test.ts": 118, "src/renderer/src/runtime/native-chat/host-capabilities/structured-chat-host-permission.test.ts": 523, "src/renderer/src/runtime/web-session-tabs-sync/placement/structured-conversation-tab-replacement.test.ts": 2029, - "src/renderer/src/runtime/native-chat/tab-retirement/structured-launch-cancel-layout-owner.test.ts": 1985, "src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-chat-tab-order.test.ts": 529, "src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-conversion-publish.test.ts": 1608, "src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-editor-diff-tabs.test.ts": 526, @@ -6563,7 +6489,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/browser/creation/web-runtime-browser-link-session.test.ts": 1964, "src/renderer/src/runtime/web-session-tabs-sync/closing/web-session-close-replay.test.ts": 1119, "src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-open-files-batch-equivalence.test.ts": 1478, "src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-restored-placeholder-identity.test.ts": 985, @@ -6581,10 +6506,8 @@ "src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-tabs-sync-mirror-identity.test.ts": 2524, "src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-mirrored-draft-close.test.ts": 1833, "src/renderer/src/runtime/web-session-tabs-sync/agent-status/web-session-tabs-sync-remote-status-title-flap.test.ts": 1715, - "src/renderer/src/runtime/web-session-tabs-sync/agent-status/web-session-tabs-sync-sleep-activity.test.ts": 1010, "src/renderer/src/runtime/web-session-tabs-sync/agent-status/web-session-tabs-sync-stale-spinner.test.ts": 921, "src/renderer/src/runtime/web-session-tabs-sync/tracking/web-session-tabs-sync-tracking-teardown.test.ts": 940, - "src/renderer/src/runtime/web-session-tabs-sync/subscriptions/web-session-tabs-sync-unverifiable-host.test.tsx": 2424, "src/renderer/src/runtime/web-session-tabs-sync/subscriptions/web-session-tabs-sync-visibility-collision.test.tsx": 2699, "src/renderer/src/runtime/web-session-tabs-sync/subscriptions/web-session-tabs-sync-window-visibility.test.tsx": 2589, "src/renderer/src/runtime/web-session-tabs-sync/subscriptions/web-session-tabs-sync-worktree-switch.test.tsx": 2625, @@ -6601,7 +6524,6 @@ "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-editor-views.test.ts": 2098, "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/runtime/workspace-layout/frames/workspace-layout-frame-tab-props.test.ts": 2852, @@ -6616,7 +6538,6 @@ "src/renderer/src/store/github/requests/provider-request-coalescing.test.ts": 969, "src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler.test.ts": 97, "src/renderer/src/store/github/repositories/wsl-stopped-distro-poll-refusal.test.ts": 696, - "src/renderer/src/store/workspaces/host-isolation/host-twin-isolation.test.ts": 1889, "src/renderer/src/store/workspaces/host-isolation/host-twin-worktree-purge.test.ts": 1945, "src/renderer/src/store/plugins/localization/plugin-language-packs-startup.test.ts": 435, "src/renderer/src/store/plugins/localization/plugin-language-packs.test.ts": 377, @@ -6653,7 +6574,6 @@ "src/renderer/src/store/slices/agent-status/agent-status-worktree-purge-leak.test.ts": 1744, "src/renderer/src/store/slices/agent-status/agent-status.test.ts": 2129, "src/renderer/src/store/repos/all-host-catalog-settlement.test.ts": 1955, - "src/renderer/src/store/slices/worktrees/teardown/ambiguous-owner-warning-worktree-removal-leak.test.ts": 2101, "src/renderer/src/store/slices/browser/annotations/browser-annotation-retention.test.ts": 8178, "src/renderer/src/store/slices/browser/cleanup/browser-cleanup-close.test.ts": 1911, "src/renderer/src/store/slices/browser/cleanup/browser-mount-admission-removal.test.ts": 1982, @@ -6664,7 +6584,6 @@ "src/renderer/src/store/slices/browser/tabs/browser-tab-creation-placement.test.ts": 1886, "src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts": 2007, "src/renderer/src/store/slices/browser/browser.test.ts": 2001, - "src/renderer/src/store/slices/worktrees/teardown/bulk-worktree-purge-terminal-maps-leak.test.ts": 1727, "src/renderer/src/store/terminals/codex-restart-notice-lifecycle.test.ts": 1685, "src/renderer/src/store/slices/tabs/content-tabs-from-main-frames.test.ts": 2025, "src/renderer/src/store/slices/tabs/content-tabs-paired-server-workspace.test.ts": 1923, @@ -6679,7 +6598,6 @@ "src/renderer/src/store/slices/editor/checks/editor-check-details-tabs.test.ts": 1814, "src/renderer/src/store/slices/editor/closing/editor-close-background-file.test.ts": 893, "src/renderer/src/store/slices/editor/closing/editor-close-document-siblings.test.ts": 1317, - "src/renderer/src/store/slices/editor/closing/editor-close-file-cleanup.test.ts": 2000, "src/renderer/src/store/slices/editor/closing/editor-close-file-stale-active.test.ts": 1806, "src/renderer/src/store/slices/editor/closing/editor-close-pinned-sibling.test.ts": 924, "src/renderer/src/store/slices/editor/closing/editor-close-workspace-selection.test.ts": 1850, @@ -6711,7 +6629,6 @@ "src/renderer/src/store/github/pull-requests/github-linked-review-clear-ownership.test.ts": 891, "src/renderer/src/store/slices/editor/git/github-post-operation-owner.test.ts": 2062, "src/renderer/src/store/github/pull-requests/github-pr-branch-direct-refresh-scope.test.ts": 667, - "src/renderer/src/store/github/pull-requests/github-pr-branch-fallback-results.test.ts": 658, "src/renderer/src/store/github/pull-requests/github-pr-branch-linked-pr-divergence.test.ts": 662, "src/renderer/src/store/github/comments/github-pr-comment-read-order.test.ts": 570, "src/renderer/src/store/github/comments/github-pr-comments.test.ts": 746, @@ -6719,7 +6636,6 @@ "src/renderer/src/store/github/refresh/github-pr-manual-refresh-broadcast.test.ts": 693, "src/renderer/src/store/github/refresh/github-pr-refresh-states-leak.test.ts": 1327, "src/renderer/src/store/github/pull-requests/github-pr-request-lifetime.test.ts": 1458, - "src/renderer/src/store/github/projects/github-project-view-tables.test.ts": 656, "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, @@ -6781,10 +6697,8 @@ "src/renderer/src/store/slices/worktrees/create/sparse-presets.test.ts": 217, "src/renderer/src/store/slices/ssh/ssh.test.ts": 1843, "src/renderer/src/lib/workspace/activation/active-worktree-removal-successor.test.ts": 1867, - "src/renderer/src/store/slices/worktrees/session/store-active-worktree-selection.test.ts": 2039, "src/renderer/src/store/terminals/store-create-tab-start-in-main.test.ts": 1801, "src/renderer/src/store/slices/tabs/store-open-to-side-layout-owner.test.ts": 1919, - "src/renderer/src/store/slices/browser/hydration/store-session-browser-hydration.test.ts": 1906, "src/renderer/src/store/repos/store-session-cascades.test.ts": 1775, "src/renderer/src/store/slices/editor/hydration/store-session-editor-hydration.test.ts": 1719, "src/renderer/src/store/terminals/store-session-terminal-reconnect.test.ts": 2279, @@ -6793,7 +6707,6 @@ "src/renderer/src/store/terminals/store-sleep-exact-runtime-stop.test.ts": 1842, "src/renderer/src/store/terminals/store-sleep-pane-hibernation.test.ts": 1932, "src/renderer/src/store/terminals/store-sleep-runtime-convergence.test.ts": 1767, - "src/renderer/src/store/terminals/store-sleep-twin-host-owner.test.ts": 1706, "src/renderer/src/store/slices/worktrees/teardown/store-worktree-removal-cascade.test.ts": 1786, "src/renderer/src/store/slices/worktrees/teardown/tab-worktree-orphan-map-purge-leak.test.ts": 1936, "src/renderer/src/store/slices/tabs/tabs-close-dangling-group.test.ts": 1849, @@ -6815,7 +6728,6 @@ "src/renderer/src/store/terminals/terminal-tab-owner-index.test.ts": 50, "src/renderer/src/store/terminals/terminal-tab-recovery-remount.test.ts": 1791, "src/renderer/src/store/terminals/terminal-tab-retirement-store.test.ts": 1955, - "src/renderer/src/store/terminals/terminal-tab-title-batch.test.ts": 1749, "src/renderer/src/store/terminals/terminals-hydration-canonical-pty-overlap.test.ts": 1946, "src/renderer/src/store/terminals/terminals-hydration-canonical-rows.test.ts": 1680, "src/renderer/src/store/slices/ui/ui-agent-send-target.test.ts": 760, @@ -6889,7 +6801,6 @@ "src/renderer/src/store/terminals/workspace-terminal-placeholders.test.ts": 302, "src/renderer/src/store/slices/runtime-status/views/use-runtime-status-view.test.tsx": 1979, "src/renderer/src/store/workspace-layout/workspace-layout-cache.test.ts": 63, - "src/renderer/src/store/workspace-layout/frames/workspace-layout-frame-store-patch.test.ts": 2284, "src/renderer/src/store/slices/worktrees/listing/worktree-host-collision-index.test.ts": 1875, "src/renderer/src/web/preload-api/web-agent-session-attachment-upload.test.ts": 1588, "src/renderer/src/web/preload-api/web-chat-permission-normalization.test.ts": 293, @@ -7852,7 +7763,6 @@ "tests/e2e/agent-launch-cli.unit.test.ts": 2379, "tests/e2e/agent-launch-setup-choice.unit.test.ts": 2657, "tests/e2e/agent-model-catalog-renderer-cache.unit.test.ts": 2029, - "tests/e2e/ai-vault-account-stream.unit.test.ts": 4506, "tests/e2e/ai-vault-manual-name-clear.unit.test.ts": 21206, "tests/e2e/automation-chat-reopen.unit.test.ts": 6262, @@ -7898,13 +7808,11 @@ "tests/e2e/linear-store.unit.test.ts": 519, "tests/e2e/linear-write-lifetime.unit.test.ts": 5214, "tests/e2e/multi-workspace-typing-bench.unit.test.ts": 550, - "tests/e2e/native-chat-image-runtime-context.unit.test.ts": 2124, "tests/e2e/native-chat-live-history.unit.test.ts": 3258, "tests/e2e/native-chat-rewind-boundary.unit.test.ts": 2977, "tests/e2e/native-chat-ssh-transcript.unit.test.ts": 1166, "tests/e2e/native-chat-startup-option-pickers.unit.test.ts": 9377, - "tests/e2e/native-chat-transcript-reasoning.unit.test.ts": 3341, "tests/e2e/nested-agent-idle-owner.unit.test.ts": 2469, "tests/e2e/omp-child-session-recovery.unit.test.ts": 2205, "tests/e2e/omp-retired-host-renderer.unit.test.ts": 2546, @@ -7928,7 +7836,6 @@ "tests/e2e/source-control-action-phone-launch.unit.test.ts": 746, "tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts": 413, "tests/e2e/structured-agent-session-launch-admission.unit.test.ts": 4762, - "tests/e2e/structured-agent-session-launch-continuation.unit.test.ts": 23572, "tests/e2e/structured-agent-session-read-owner.unit.test.ts": 6912, "tests/e2e/structured-attention-headless-delivery.unit.test.ts": 328, "tests/e2e/structured-attention-prompt-relay.unit.test.ts": 14045, diff --git a/config/scripts/static-analysis/ratchets/renderer-state/check-terminal-parking-ownership-ratchet.mjs b/config/scripts/static-analysis/ratchets/renderer-state/check-terminal-parking-ownership-ratchet.mjs index 112b837bbb7..8d823b050a9 100644 --- a/config/scripts/static-analysis/ratchets/renderer-state/check-terminal-parking-ownership-ratchet.mjs +++ b/config/scripts/static-analysis/ratchets/renderer-state/check-terminal-parking-ownership-ratchet.mjs @@ -125,7 +125,7 @@ const EFFECT_BOUNDARIES = new Set([ `${WATCHERS}terminal-parked-pty-watcher.ts#startParkedPtyWatcher`, `${RENDERER}components/terminal-pane/parking/capture/parked-terminal-buffer-capture.ts#captureParkedTerminalBuffers`, `${RENDERER}lib/agent-session/resume/sleeping-agent-session-launch.ts#launchSleepingAgentSession`, - `${RENDERER}lib/host-mirror-handle-gap-wait.ts#parkUntilHostMirrorHandleLands`, + `${RENDERER}lib/agent-session/resume/host-mirror-handle-gap-wait.ts#parkUntilHostMirrorHandleLands`, `${RENDERER}runtime/web-session-tabs-sync/hydration/host-session-mirror-hydration.ts#parkUntilHostSessionMirrorHydrates` ]) const ENUMERATORS = new Set(['entries', 'values', 'keys', 'assign']) diff --git a/config/workspace-record-read-baseline.txt b/config/workspace-record-read-baseline.txt index 418a6c1e1ad..f6555eb8c82 100644 --- a/config/workspace-record-read-baseline.txt +++ b/config/workspace-record-read-baseline.txt @@ -30,14 +30,14 @@ 1 src/renderer/src/lib/browser/navigation/http-link-localhost-route.ts # P5b-2 must clear: optional state field defaults to empty; extracted from http-link-routing.ts 1 src/renderer/src/lib/workspace/ownership/connection-owner-resolution.ts # P5b-2 must clear: optional-chain compare of a previous slice 2 src/renderer/src/lib/workspace/ownership/direct-ssh-target-scope.ts # P5b-2 must clear: optional input fields default to empty -3 src/renderer/src/lib/duplicate-paired-servers.ts # P5b-2 must clear: optional state fields default to empty +3 src/renderer/src/lib/workspace/ownership/duplicate-paired-servers.ts # P5b-2 must clear: optional state fields default to empty 1 src/renderer/src/lib/workspace/ownership/folder-workspace-runtime-owner.ts # P5b-2 must clear: loosely typed state param 1 src/renderer/src/runtime/hosts/wsl/local-project-runtime-workspace.ts # P5b-2 must clear: optional state field defaults to empty -1 src/renderer/src/lib/resolved-worktree-execution-host.ts # P5b-2 must clear: loosely typed state param +1 src/renderer/src/lib/workspace/ownership/resolved-worktree-execution-host.ts # P5b-2 must clear: loosely typed state param 2 src/renderer/src/lib/workspace/ownership/runtime-session-mirror-owners.ts # P5b-2 must clear: optional state fields default to empty 2 src/renderer/src/lib/workspace/ownership/terminal-worktree-route.ts # P5b-2 must clear: the unattributed-twin check reads both catalogs directly 3 src/renderer/src/lib/typing-latency/diagnostic-summary.ts # P5b-2 must clear: optional state field -2 src/renderer/src/lib/unread-badge-count.ts # reads a passed-in copy +2 src/renderer/src/attention/unread/unread-badge-count.ts # reads a passed-in copy 1 src/renderer/src/lib/workspace/paths/workspace-directory.ts # P5b-2 must clear: optional state field defaults to empty 2 src/renderer/src/lib/workspace/ownership/workspace-terminal-host-authority.ts # P5b-2 must clear: optional state fields 1 src/renderer/src/lib/workspace/activation/initial-surface/worktree-initial-terminal-seeding.ts # P5b-2 must clear: treats an undefined field as a narrow adapter diff --git a/docs/site/content/docs/cli/reference.mdx b/docs/site/content/docs/cli/reference.mdx index 12cfa96f2b0..fb1011130dc 100644 --- a/docs/site/content/docs/cli/reference.mdx +++ b/docs/site/content/docs/cli/reference.mdx @@ -233,6 +233,21 @@ orca chat rename --name "Migrate auth" Renames a chat tab, the same as renaming it by hand. `--session` takes the `sessionId` that `orca agent launch` prints. Run inside a chat, it defaults to that chat; with `--environment` it is required. +Agents that run as chats are read and messaged with `chat` commands. `--session` takes the session id from `chat list` or the handle `agent launch` returns. + +```bash +orca chat list --json +orca chat list --state working --json +orca chat read --session --limit 10 --json +orca chat send --session --text "Run the tests, then summarize failures" --json +orca chat send --session --text "" --wait --timeout-ms 600000 --json +orca chat wait --session --timeout-ms 600000 --json +``` + +`chat read` returns the newest messages, tool calls, errors, approvals and questions; an approval or question waiting for an answer has `pending: true`. `chat send` sends the text as your message. While the agent is working, hosts with a message queue hold it until the turn ends and report `delivery: "queued"`. A chat that restarted since it was read refuses the send. `--text-file -` reads the message from stdin. + +`chat send --wait` and `chat wait` return once the chat's own turn settles, in the words `chat list` uses: `settled: "done"`, or `settled: "blocked"` when an approval or question needs an answer. Background agents the chat started can still show as `working` or `waiting` in `chat list`. They print the entries since the last user message. A wait past `--timeout-ms` returns `settled: "timeout"`, and a message held in a stopped or failed queue returns `settled: "held"`; both exit 1. `chat read --json` returns a `cursor` for the newest row read, and `truncated: true` when older rows it needed were past the 200-row read. `chat list --state` takes `working`, `blocked`, `waiting` or `done`. Paired hosts (`--environment`, `--pairing-code`) can list chats but not read, send or wait yet. + ## Files ```bash diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellBridge.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellBridge.kt index 045cce54908..99f8bfc2713 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellBridge.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellBridge.kt @@ -38,7 +38,7 @@ internal enum class MobileWebShellBridgeInstall { /** The prop is false, so nothing is registered and Phase B behaviour is byte-identical. */ SKIP, INSTALL, - /** The WebView provider is older than `WEB_MESSAGE_LISTENER` (Chromium 88). Terminal. */ + /** The WebView provider is older than `WEB_MESSAGE_LISTENER` (Chromium 83). Terminal. */ UNAVAILABLE } diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellDocument.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellDocument.kt index af1aff6a343..0d8f77c5fc5 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellDocument.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellDocument.kt @@ -201,7 +201,7 @@ internal class MobileWebShellDocument(private val context: Context) { view.destroy() } - // Keep explicit settings for the Chromium 83 floor, even where newer WebViews ignore deprecated options. + // Keep explicit settings even where newer WebViews ignore deprecated options; the floor is Chromium 101. // B4 requires device proofs: no network, persistent state, file/content access, cleartext or navigation escape. @Suppress("DEPRECATION") private fun createWebView(): WebView { diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellNetworkApiBlocker.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellNetworkApiBlocker.kt index 4c0397fdd0a..0b94103df6e 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellNetworkApiBlocker.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellNetworkApiBlocker.kt @@ -17,7 +17,7 @@ internal val MOBILE_WEB_SHELL_NETWORK_API_BLOCKER = """ })(); """.trimIndent() -/** Query document-start-script capability (Chromium 83 floor), not version strings. */ +/** Query capability, not version strings; stable WebView has it from Chromium 101. */ internal fun installMobileWebShellNetworkApiBlocker( webView: WebView, allowedOrigin: String diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/OrcaMobileWebShellModule.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/OrcaMobileWebShellModule.kt index abba9fd7675..e08436bd126 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/OrcaMobileWebShellModule.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/OrcaMobileWebShellModule.kt @@ -8,6 +8,8 @@ import android.content.res.Configuration import android.net.Uri import android.os.Handler import android.os.Looper +import androidx.webkit.WebViewCompat +import androidx.webkit.WebViewFeature import expo.modules.kotlin.exception.CodedException import expo.modules.kotlin.exception.Exceptions import expo.modules.kotlin.functions.Queues @@ -68,6 +70,17 @@ class OrcaMobileWebShellModule : Module() { Uri.fromFile(directory).toString() } + // Lets isolation-unavailable name the WebView to update. + Function("currentWebViewProvider") { + val context = appContext.reactContext ?: return@Function null + val info = WebViewCompat.getCurrentWebViewPackage(context) ?: return@Function null + val version = info.versionName ?: return@Function null + val name = info.applicationInfo?.loadLabel(context.packageManager)?.toString() ?: info.packageName + val hasShellFeatures = WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT) && + WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER) + mapOf("name" to name, "version" to version, "hasShellFeatures" to hasShellFeatures) + } + AsyncFunction("prepareSpareDocument") { directory: String, sessionId: String -> val activity = appContext.currentActivity ?: return@AsyncFunction false MobileWebShellSparePool.prepare(activity, directory, sessionId) diff --git a/mobile/modules/orca-mobile-web-shell/src/index.ts b/mobile/modules/orca-mobile-web-shell/src/index.ts index 97979cd7019..4e072e2efb2 100644 --- a/mobile/modules/orca-mobile-web-shell/src/index.ts +++ b/mobile/modules/orca-mobile-web-shell/src/index.ts @@ -18,7 +18,7 @@ export type OrcaMobileWebShellViewProps = ViewProps & { generationDirectory: string /** `[A-Za-z0-9_-]{1,128}`. Scopes the private origin, so every mount must mint a fresh one. */ sessionId: string - // Bridge is off by default with nothing registered. Opt-in on Android below WEB_MESSAGE_LISTENER/Chromium 88 fails isolation-unavailable instead of loading unfenced. + // Bridge is off by default with nothing registered. Opt-in on Android below WEB_MESSAGE_LISTENER/Chromium 83 fails isolation-unavailable instead of loading unfenced. bridgeEnabled?: boolean onLoadState?: (event: NativeSyntheticEvent) => void // Raw JSON from window.orcaBridge; native silently rejects other origins/frames/WebViews and envelopes above 640 KiB (MobileWebShellBridge.maxMessageByteCount). @@ -82,6 +82,23 @@ export function warmUpWebShell(): void { } } +export type WebViewProvider = { name: string; version: string; hasShellFeatures: boolean } + +// Android only: the WebView provider and whether it has the shell's fences. Null when unknown. +export function currentWebViewProvider(): WebViewProvider | null { + if (Platform.OS !== 'android') { + return null + } + const shell = requireOptionalNativeModule<{ + currentWebViewProvider?: () => WebViewProvider | null + }>('OrcaMobileWebShell') + try { + return shell?.currentWebViewProvider?.() ?? null + } catch { + return null + } +} + export { MOBILE_WEB_SHELL_FAILURE_REASONS, parseMobileWebShellLoadState, diff --git a/mobile/rpc-foundation/pilot-scenarios.json b/mobile/rpc-foundation/pilot-scenarios.json index dfd3079e39d..688d2a86b98 100644 --- a/mobile/rpc-foundation/pilot-scenarios.json +++ b/mobile/rpc-foundation/pilot-scenarios.json @@ -21045,7 +21045,7 @@ "id": "codex-reset-credit-consumed", "operation": "accounts.codex-reset-credit", "family": "components.codex-reset-credit", - "sites": ["mobile/src/components/codex-reset-credit.ts"], + "sites": ["mobile/src/accounts/usage/codex-reset-credit.ts"], "schedules": [], "deviceStore": {}, "steps": [ diff --git a/mobile/src/accounts/MobileAccountsScreen.tsx b/mobile/src/accounts/MobileAccountsScreen.tsx index a76da2ffa62..2cdb378d4b3 100644 --- a/mobile/src/accounts/MobileAccountsScreen.tsx +++ b/mobile/src/accounts/MobileAccountsScreen.tsx @@ -16,22 +16,23 @@ import { useMobileTranslation } from '../i18n/use-mobile-translation' import { styles } from './mobile-accounts-screen-styles' import { useNow } from '../hooks/use-now' import { ClaudeIcon, OpenAIIcon } from '../components/AgentIcons' +import './usage/UsageBar' import { type ProviderKey, getActiveProviderRateLimits, getInactiveProviderUsage, getOtherUsageProviders, hasActiveProviderUsage -} from '../components/AccountUsage' +} from './usage/usage-selectors' import { MobileAgentIcon } from '../components/MobileAgentIcon' import { getProviderDisplayName } from '../../../src/shared/usage-provider-windows' import { ProviderUsageWindows } from './ProviderUsageWindows' import { getActiveCodexAccountIdForRateLimitTarget, getCodexResetCreditSummary -} from '../components/codex-reset-credit' -import { CodexResetCreditAction } from '../components/CodexResetCreditAction' -import { useCodexResetCreditAction } from '../components/use-codex-reset-credit-action' +} from './usage/codex-reset-credit' +import { CodexResetCreditAction } from './usage/CodexResetCreditAction' +import { useCodexResetCreditAction } from './usage/use-codex-reset-credit-action' import { ConfirmModal } from '../components/ConfirmModal' import { NavBar } from '../components/nav-bar/NavBar' import { NavBarButton } from '../components/nav-bar/NavBarButton' diff --git a/mobile/src/accounts/ProviderUsageWindows.tsx b/mobile/src/accounts/ProviderUsageWindows.tsx index 8f9dd1e9e30..43f8b9a5be3 100644 --- a/mobile/src/accounts/ProviderUsageWindows.tsx +++ b/mobile/src/accounts/ProviderUsageWindows.tsx @@ -4,12 +4,9 @@ import { getUsageWindowSections, type UsageWindowSection } from '../../../src/shared/usage-provider-windows' -import { - getUsageBarState, - getWindowResetLabel, - UsageBar, - type ProviderRateLimits -} from '../components/AccountUsage' +import { UsageBar } from './usage/UsageBar' +import { getUsageBarState, getWindowResetLabel } from './usage/usage-selectors' +import type { ProviderRateLimits } from './accounts-snapshot' import type { Translate } from '../i18n/mobile-i18n' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { spacing } from '../theme/mobile-theme' diff --git a/mobile/src/accounts/accounts-snapshot-stream.ts b/mobile/src/accounts/accounts-snapshot-stream.ts index 09ca407fead..64ed6066c1b 100644 --- a/mobile/src/accounts/accounts-snapshot-stream.ts +++ b/mobile/src/accounts/accounts-snapshot-stream.ts @@ -1,6 +1,6 @@ import { queryOptions, skipToken } from '@tanstack/react-query' -import { AccountsSnapshotSchema, decodeAccountsSnapshot } from '../components/accounts-snapshot' -import type { AccountsSnapshot } from '../components/AccountUsage' +import { AccountsSnapshotSchema, decodeAccountsSnapshot } from './accounts-snapshot' +import type { AccountsSnapshot } from './accounts-snapshot' import { hostQueryKey, type HostQueryKey } from '../query/host-query-key' import type { PersistedHostFamily } from '../query/host-query-persistence' import type { RpcClient } from '../transport/rpc/rpc-client-contract' diff --git a/mobile/src/components/accounts-snapshot.ts b/mobile/src/accounts/accounts-snapshot.ts similarity index 100% rename from mobile/src/components/accounts-snapshot.ts rename to mobile/src/accounts/accounts-snapshot.ts diff --git a/mobile/src/components/CodexResetCreditAction.tsx b/mobile/src/accounts/usage/CodexResetCreditAction.tsx similarity index 91% rename from mobile/src/components/CodexResetCreditAction.tsx rename to mobile/src/accounts/usage/CodexResetCreditAction.tsx index 0c273fa6d19..0ba5841b6c0 100644 --- a/mobile/src/components/CodexResetCreditAction.tsx +++ b/mobile/src/accounts/usage/CodexResetCreditAction.tsx @@ -1,11 +1,11 @@ import { ActivityIndicator, Pressable, StyleSheet, Text } from 'react-native' import { RotateCcw } from 'lucide-react-native' -import { useMobileTranslation } from '../i18n/use-mobile-translation' -import { colors, feedback, radii, spacing, typography } from '../theme/mobile-theme' -import { themedStyleSheet } from '../theme/themed-styles' -import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' +import { useMobileTranslation } from '../../i18n/use-mobile-translation' +import { colors, feedback, radii, spacing, typography } from '../../theme/mobile-theme' +import { themedStyleSheet } from '../../theme/themed-styles' +import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' import type { CodexResetCreditSummary } from './codex-reset-credit' -import { ListRow } from './list/ListGroup' +import { ListRow } from '../../components/list/ListGroup' export function CodexResetCreditAction({ summary, diff --git a/mobile/src/components/AccountUsage.tsx b/mobile/src/accounts/usage/UsageBar.tsx similarity index 81% rename from mobile/src/components/AccountUsage.tsx rename to mobile/src/accounts/usage/UsageBar.tsx index 83253a3c04b..7fdcd674347 100644 --- a/mobile/src/components/AccountUsage.tsx +++ b/mobile/src/accounts/usage/UsageBar.tsx @@ -1,29 +1,9 @@ import { View, Text, ActivityIndicator, type StyleProp, type ViewStyle } from 'react-native' -import { colors, spacing, typography } from '../theme/mobile-theme' -import { themedStyleSheet } from '../theme/themed-styles' -import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' +import { colors, spacing, typography } from '../../theme/mobile-theme' +import { themedStyleSheet } from '../../theme/themed-styles' +import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' -// Re-export pure account-usage-state selectors/types to keep imports stable and tests free of RN. -export type { - RateLimitWindow, - ProviderRateLimits, - InactiveAccountUsage, - ClaudeAccountSummary, - CodexAccountSummary, - AccountsSnapshot, - ProviderKey, - UsageBarState -} from './account-usage-state' -export { - decodeAccountsSnapshot, - getActiveProviderRateLimits, - getInactiveProviderUsage, - getOtherUsageProviders, - getUsageBarState, - getWindowResetLabel, - hasActiveProviderUsage, - hasRenderableUsage -} from './account-usage-state' +import './usage-selectors' /** A meter's fill: the rounded, clamped percent and its consumption colour, shared by every usage meter. */ export function usageBarFill( diff --git a/mobile/src/components/codex-reset-credit-capability.ts b/mobile/src/accounts/usage/codex-reset-credit-capability.ts similarity index 51% rename from mobile/src/components/codex-reset-credit-capability.ts rename to mobile/src/accounts/usage/codex-reset-credit-capability.ts index 1000e16013e..f8e184c0aa9 100644 --- a/mobile/src/components/codex-reset-credit-capability.ts +++ b/mobile/src/accounts/usage/codex-reset-credit-capability.ts @@ -1,10 +1,7 @@ import { useEffect, useState } from 'react' -import { CODEX_RESET_CREDIT_RUNTIME_CAPABILITY } from '../../../src/shared/account-runtime-capabilities' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import { startRuntimeCapabilityProbe } from '../transport/connection/runtime-capability-probe' - -// Use shared capability constant so host/mobile versions cannot silently drift. -export const MOBILE_CODEX_RESET_CREDIT_CAPABILITY = CODEX_RESET_CREDIT_RUNTIME_CAPABILITY +import { CODEX_RESET_CREDIT_RUNTIME_CAPABILITY } from '../../../../src/shared/account-runtime-capabilities' +import type { RpcClient } from '../../transport/rpc/rpc-client-contract' +import { startRuntimeCapabilityProbe } from '../../transport/connection/runtime-capability-probe' export function useCodexResetCreditCapability( client: RpcClient | null, @@ -18,7 +15,7 @@ export function useCodexResetCreditCapability( return } return startRuntimeCapabilityProbe(client, (capabilities) => { - setSupported(capabilities.includes(MOBILE_CODEX_RESET_CREDIT_CAPABILITY)) + setSupported(capabilities.includes(CODEX_RESET_CREDIT_RUNTIME_CAPABILITY)) }) }, [client, connected]) diff --git a/mobile/src/components/codex-reset-credit-consume-operations.ts b/mobile/src/accounts/usage/codex-reset-credit-consume-operations.ts similarity index 91% rename from mobile/src/components/codex-reset-credit-consume-operations.ts rename to mobile/src/accounts/usage/codex-reset-credit-consume-operations.ts index ef3c719fd7b..2f7c685034d 100644 --- a/mobile/src/components/codex-reset-credit-consume-operations.ts +++ b/mobile/src/accounts/usage/codex-reset-credit-consume-operations.ts @@ -1,5 +1,5 @@ -import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc/rpc-operation' -import { rpcResultVariant } from '../transport/rpc/rpc-operation-result-reader' +import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rpc/rpc-operation' +import { rpcResultVariant } from '../../transport/rpc/rpc-operation-result-reader' import { codexResetCreditReplySchema } from './codex-reset-credit-reply-schema' // Use require-result-or-throw-message so confirm shows host sentence. Keep payload opaque: call-site decodeResetResult alone checks attempt scope/snapshot. diff --git a/mobile/src/components/codex-reset-credit-reply-schema.ts b/mobile/src/accounts/usage/codex-reset-credit-reply-schema.ts similarity index 100% rename from mobile/src/components/codex-reset-credit-reply-schema.ts rename to mobile/src/accounts/usage/codex-reset-credit-reply-schema.ts diff --git a/mobile/src/components/codex-reset-credit.ts b/mobile/src/accounts/usage/codex-reset-credit.ts similarity index 98% rename from mobile/src/components/codex-reset-credit.ts rename to mobile/src/accounts/usage/codex-reset-credit.ts index 47bf70bfcad..fced6e3117c 100644 --- a/mobile/src/components/codex-reset-credit.ts +++ b/mobile/src/accounts/usage/codex-reset-credit.ts @@ -1,20 +1,20 @@ import { buildCodexResetCreditExpectedScope, type CodexResetCreditExpectedScope -} from '../../../src/shared/codex-reset-credit-scope' +} from '../../../../src/shared/codex-reset-credit-scope' import { codexResetCreditConsume, type MobileCodexResetCreditRpcSender, type MobileCodexResetCreditSendScope } from './codex-reset-credit-consume-operations' import { CodexResetCreditExpectedScopeSchema } from './codex-reset-credit-reply-schema' -import { randomV4Uuid } from '../platform/random-v4-uuid' -import { translate } from '../i18n/mobile-i18n' +import { randomV4Uuid } from '../../platform/random-v4-uuid' +import { translate } from '../../i18n/mobile-i18n' import { decodeAccountsSnapshot, type AccountsSnapshot, type ProviderRateLimits -} from './accounts-snapshot' +} from '../accounts-snapshot' export type CodexResetCreditOutcome = 'reset' | 'nothingToReset' | 'noCredit' | 'alreadyRedeemed' diff --git a/mobile/src/components/account-usage-state.ts b/mobile/src/accounts/usage/usage-selectors.ts similarity index 83% rename from mobile/src/components/account-usage-state.ts rename to mobile/src/accounts/usage/usage-selectors.ts index 23d4c02485c..f0f3b6d3311 100644 --- a/mobile/src/components/account-usage-state.ts +++ b/mobile/src/accounts/usage/usage-selectors.ts @@ -1,29 +1,13 @@ // Keep shapes aligned with shared types/rate-limit-types without pulling Electron-coupled desktop graph into mobile. -// Pure RN-free selectors stay directly testable; AccountUsage re-exports them with UsageBar. -import { formatResetCountdown } from '../../../src/shared/rate-limit-reset-format' -import { hasUsageData } from '../../../src/shared/usage-provider-windows' +import { formatResetCountdown } from '../../../../src/shared/rate-limit-reset-format' +import { hasUsageData } from '../../../../src/shared/usage-provider-windows' import { ProviderRateLimitsSchema, type AccountsSnapshot, type InactiveAccountUsage, type ProviderRateLimits, type RateLimitWindow -} from './accounts-snapshot' - -export { - AccountsSnapshotSchema, - decodeAccountsSnapshot, - ProviderRateLimitsSchema, - RateLimitRuntimeTargetSchema, - type AccountProviderRateLimits, - type AccountsSnapshot, - type ClaudeAccountSummary, - type CodexAccountSummary, - type InactiveAccountUsage, - type ProviderRateLimits, - type RateLimitRuntimeTarget, - type RateLimitWindow -} from './accounts-snapshot' +} from '../accounts-snapshot' export type ProviderKey = 'claude' | 'codex' diff --git a/mobile/src/components/use-codex-reset-credit-action.ts b/mobile/src/accounts/usage/use-codex-reset-credit-action.ts similarity index 93% rename from mobile/src/components/use-codex-reset-credit-action.ts rename to mobile/src/accounts/usage/use-codex-reset-credit-action.ts index cb0dbcda7f8..4e33f0e9afc 100644 --- a/mobile/src/components/use-codex-reset-credit-action.ts +++ b/mobile/src/accounts/usage/use-codex-reset-credit-action.ts @@ -1,10 +1,10 @@ import { useCallback, useMemo, useRef, useState } from 'react' -import type { CodexResetCreditExpectedScope } from '../../../src/shared/codex-reset-credit-scope' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import { translate } from '../i18n/mobile-i18n' -import type { Translate } from '../i18n/mobile-i18n' -import { useMobileTranslation } from '../i18n/use-mobile-translation' -import type { AccountsSnapshot } from './account-usage-state' +import type { CodexResetCreditExpectedScope } from '../../../../src/shared/codex-reset-credit-scope' +import type { RpcClient } from '../../transport/rpc/rpc-client-contract' +import { translate } from '../../i18n/mobile-i18n' +import type { Translate } from '../../i18n/mobile-i18n' +import { useMobileTranslation } from '../../i18n/use-mobile-translation' +import type { AccountsSnapshot } from '../accounts-snapshot' import { getCodexResetCreditOutcomeCopy, getCodexResetCreditScope, diff --git a/mobile/src/accounts/use-mobile-accounts-snapshot.ts b/mobile/src/accounts/use-mobile-accounts-snapshot.ts index d4370bb5310..d14fb47b4b9 100644 --- a/mobile/src/accounts/use-mobile-accounts-snapshot.ts +++ b/mobile/src/accounts/use-mobile-accounts-snapshot.ts @@ -1,7 +1,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react' import { hashKey, useQuery, useQueryClient } from '@tanstack/react-query' -import { AccountsSnapshotError, decodeAccountsSnapshot } from '../components/accounts-snapshot' -import type { AccountsSnapshot } from '../components/AccountUsage' +import { AccountsSnapshotError, decodeAccountsSnapshot } from './accounts-snapshot' +import type { AccountsSnapshot } from './accounts-snapshot' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { holdsRestoredHostQueryData } from '../query/host-query-persistence' import type { ConnectionState } from '../transport/connection/connection-state' diff --git a/mobile/src/components/accounts-snapshot.test.ts b/mobile/src/components/accounts-snapshot.test.ts deleted file mode 100644 index 89e0bf84934..00000000000 --- a/mobile/src/components/accounts-snapshot.test.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { decodeAccountsSnapshot } from './accounts-snapshot' - -function makeSnapshot(): unknown { - return { - extensionField: { retained: true }, - claude: { - accounts: [], - activeAccountId: null, - activeAccountIdsByRuntime: { host: null, wsl: {} } - }, - codex: { - accounts: [ - { - id: 'codex-host', - email: 'host@example.com', - managedHomeRuntime: 'host', - wslDistro: null, - updatedAt: 100, - extensionField: 'account-extra' - } - ], - activeAccountId: 'codex-host', - activeAccountIdsByRuntime: { - host: 'codex-host', - wsl: { Ubuntu: 'codex-wsl' } - } - }, - rateLimits: { - extensionField: 'limits-extra', - claude: null, - codex: { - provider: 'codex', - session: { - usedPercent: 100, - windowMinutes: 300, - resetsAt: 200, - resetDescription: 'soon' - }, - weekly: null, - rateLimitResetCredits: { - availableCount: 1, - totalEarnedCount: 2, - nextExpiresAt: 300, - credits: [{ status: 'available', expiresAt: 300, grantedAt: 50 }] - }, - updatedAt: 100, - error: null, - status: 'ok', - extensionField: 'provider-extra' - }, - claudeTarget: { runtime: 'host', wslDistro: null }, - codexTarget: { runtime: 'host', wslDistro: null }, - inactiveClaudeAccounts: [], - inactiveCodexAccounts: [ - { - accountId: 'codex-inactive', - rateLimits: null, - updatedAt: 99, - isFetching: false - } - ] - } - } -} - -function setPath(root: unknown, path: string[], value: unknown): void { - let current: unknown = root - for (const segment of path.slice(0, -1)) { - if (!current || typeof current !== 'object' || Array.isArray(current)) { - throw new Error(`Invalid fixture path: ${path.join('.')}`) - } - current = (current as Record)[segment] - } - if (!current || typeof current !== 'object' || Array.isArray(current)) { - throw new Error(`Invalid fixture path: ${path.join('.')}`) - } - const record = current as Record - record[path.at(-1)!] = value -} - -describe('decodeAccountsSnapshot', () => { - it('validates nested account/rate-limit state and preserves forward-compatible fields', () => { - const snapshot = decodeAccountsSnapshot(makeSnapshot()) - - expect(snapshot.extensionField).toEqual({ retained: true }) - expect(snapshot.codex.accounts[0]?.extensionField).toBe('account-extra') - expect(snapshot.rateLimits.extensionField).toBe('limits-extra') - expect(snapshot.rateLimits.codex?.extensionField).toBe('provider-extra') - }) - - it('defaults missing runtime targets for older host-only snapshots', () => { - const raw = makeSnapshot() as { - rateLimits: { claudeTarget?: unknown; codexTarget?: unknown } - } - delete raw.rateLimits.claudeTarget - delete raw.rateLimits.codexTarget - - const snapshot = decodeAccountsSnapshot(raw) - - expect(snapshot.rateLimits.claudeTarget).toEqual({ runtime: 'host', wslDistro: null }) - expect(snapshot.rateLimits.codexTarget).toEqual({ runtime: 'host', wslDistro: null }) - }) - - it.each([ - ['account arrays', ['codex', 'accounts'], {}], - ['active account IDs', ['codex', 'activeAccountId'], 42], - ['runtime selections', ['codex', 'activeAccountIdsByRuntime', 'wsl'], []], - ['targets', ['rateLimits', 'codexTarget', 'runtime'], 'remote'], - ['provider identity', ['rateLimits', 'codex', 'provider'], 'claude'], - ['inactive account arrays', ['rateLimits', 'inactiveCodexAccounts'], {}], - ['window percentages', ['rateLimits', 'codex', 'session', 'usedPercent'], 101], - ['credit counts', ['rateLimits', 'codex', 'rateLimitResetCredits', 'availableCount'], -1], - [ - 'credit status', - ['rateLimits', 'codex', 'rateLimitResetCredits', 'credits'], - [{ status: '', expiresAt: 300, grantedAt: 50 }] - ], - ['credit expiry', ['rateLimits', 'codex', 'rateLimitResetCredits', 'nextExpiresAt'], 'soon'] - ] satisfies Array<[string, string[], unknown]>)('rejects malformed %s', (_name, path, value) => { - const snapshot = makeSnapshot() - setPath(snapshot, path, value) - - expect(() => decodeAccountsSnapshot(snapshot)).toThrow('Invalid accounts snapshot from host') - }) - - it('rejects a host target that smuggles a WSL distro', () => { - const snapshot = makeSnapshot() - setPath(snapshot, ['rateLimits', 'codexTarget', 'wslDistro'], 'Ubuntu') - - expect(() => decodeAccountsSnapshot(snapshot)).toThrow('Invalid accounts snapshot from host') - }) -}) diff --git a/mobile/src/device-store/device-store-contract.ts b/mobile/src/device-store/device-store-contract.ts index be677c45372..ee3683b62d4 100644 --- a/mobile/src/device-store/device-store-contract.ts +++ b/mobile/src/device-store/device-store-contract.ts @@ -1,4 +1,4 @@ -import type { GenerationFileSystem } from '../mobile-web-shell/generation-store-file-system' +import type { GenerationFileSystem } from '../mobile-web-shell/generations/generation-store-file-system' import type { DeviceStoreRoots } from './device-store-files' import type { DeviceStoreKeychain } from './device-store-key' import type { DeviceStoreTable } from './device-store-seal' diff --git a/mobile/src/device-store/device-store-eviction.ts b/mobile/src/device-store/device-store-eviction.ts index 42a2c719764..dc385540b6e 100644 --- a/mobile/src/device-store/device-store-eviction.ts +++ b/mobile/src/device-store/device-store-eviction.ts @@ -1,10 +1,10 @@ -import { joinUri } from '../mobile-web-shell/generation-cache-uri' +import { joinUri } from '../mobile-web-shell/generations/generation-cache-uri' import type { GenerationDirectoryEntry, GenerationFileListing, GenerationFileSystem -} from '../mobile-web-shell/generation-store-file-system' -import { deriveHostCacheKey } from '../mobile-web-shell/host-cache-key' +} from '../mobile-web-shell/generations/generation-store-file-system' +import { deriveHostCacheKey } from '../mobile-web-shell/generations/host-cache-key' import { DEVICE_STORE_BUCKETS, DRAFT_TMP_SUFFIX, promoteLoneDraftTmp } from './device-store-files' import type { DeviceStoreTable } from './device-store-seal' diff --git a/mobile/src/device-store/device-store-files.ts b/mobile/src/device-store/device-store-files.ts index a7b65f057c5..51ee84f7132 100644 --- a/mobile/src/device-store/device-store-files.ts +++ b/mobile/src/device-store/device-store-files.ts @@ -1,9 +1,9 @@ import { sha256 } from '@noble/hashes/sha256' import { bytesToHex } from '@noble/hashes/utils' import type { AESEncryptionKey } from 'expo-crypto' -import { joinUri } from '../mobile-web-shell/generation-cache-uri' -import type { GenerationFileSystem } from '../mobile-web-shell/generation-store-file-system' -import { deriveHostCacheKey } from '../mobile-web-shell/host-cache-key' +import { joinUri } from '../mobile-web-shell/generations/generation-cache-uri' +import type { GenerationFileSystem } from '../mobile-web-shell/generations/generation-store-file-system' +import { deriveHostCacheKey } from '../mobile-web-shell/generations/host-cache-key' import { openDeviceStoreValue, type DeviceStoreTable, diff --git a/mobile/src/device-store/device-store.ts b/mobile/src/device-store/device-store.ts index adbb20ff677..849871cef76 100644 --- a/mobile/src/device-store/device-store.ts +++ b/mobile/src/device-store/device-store.ts @@ -6,7 +6,7 @@ import type { import type { AESEncryptionKey } from 'expo-crypto' import { Directory, Paths } from 'expo-file-system' import { AppState } from 'react-native' -import { createExpoGenerationFileSystem } from '../mobile-web-shell/generation-store-file-system' +import { createExpoGenerationFileSystem } from '../mobile-web-shell/generations/generation-store-file-system' import { loadStoredHostProfiles } from '../host-catalog/host-metadata-store' import { readPairingKeychainItem, diff --git a/mobile/src/diagnostics/mobile-web-shell-update-failure-row.tsx b/mobile/src/diagnostics/mobile-web-shell-update-failure-row.tsx index 78889ea5e51..b11d739e5ac 100644 --- a/mobile/src/diagnostics/mobile-web-shell-update-failure-row.tsx +++ b/mobile/src/diagnostics/mobile-web-shell-update-failure-row.tsx @@ -1,7 +1,7 @@ import { useEffect, useState } from 'react' import { Text, View } from 'react-native' import type { MobileWebShellUpdateFailure } from '../mobile-web-shell/mobile-web-shell-update-failure' -import { processGenerationStore } from '../mobile-web-shell/process-generation-store' +import { processGenerationStore } from '../mobile-web-shell/generations/process-generation-store' import { loadHosts } from '../host-catalog/host-store' import { formatUpdateFailure } from './mobile-web-shell-update-failure-copy' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' diff --git a/mobile/src/home/tabs/MobileHomeUsageTab.tsx b/mobile/src/home/tabs/MobileHomeUsageTab.tsx index 3aebd0acebb..0f97179ff0c 100644 --- a/mobile/src/home/tabs/MobileHomeUsageTab.tsx +++ b/mobile/src/home/tabs/MobileHomeUsageTab.tsx @@ -7,13 +7,13 @@ import Animated, { useSharedValue, withTiming } from 'react-native-reanimated' +import { usageBarFill } from '../../accounts/usage/UsageBar' import { getUsageBarState, getWindowResetLabel, - usageBarFill, - type AccountsSnapshot, type ProviderKey -} from '../../components/AccountUsage' +} from '../../accounts/usage/usage-selectors' +import type { AccountsSnapshot } from '../../accounts/accounts-snapshot' import { ClaudeIcon, OpenAIIcon } from '../../components/AgentIcons' import { useNow } from '../../hooks/use-now' import { useMobileTranslation } from '../../i18n/use-mobile-translation' diff --git a/mobile/src/home/tabs/home-usage-cards.test.ts b/mobile/src/home/tabs/home-usage-cards.test.ts index b8757f26084..2c5d9145d90 100644 --- a/mobile/src/home/tabs/home-usage-cards.test.ts +++ b/mobile/src/home/tabs/home-usage-cards.test.ts @@ -1,8 +1,5 @@ import { describe, expect, it } from 'vitest' -import type { - AccountProviderRateLimits, - AccountsSnapshot -} from '../../components/account-usage-state' +import type { AccountProviderRateLimits, AccountsSnapshot } from '../../accounts/accounts-snapshot' import { selectHomeUsageCards } from './home-usage-cards' function limits( diff --git a/mobile/src/home/tabs/home-usage-cards.ts b/mobile/src/home/tabs/home-usage-cards.ts index df89a46d8cb..a10f916c5fd 100644 --- a/mobile/src/home/tabs/home-usage-cards.ts +++ b/mobile/src/home/tabs/home-usage-cards.ts @@ -3,11 +3,10 @@ import { getInactiveProviderUsage, hasActiveProviderUsage, hasRenderableUsage, - type AccountsSnapshot, - type ProviderKey, - type ProviderRateLimits -} from '../../components/account-usage-state' -import { getActiveCodexAccountIdForRateLimitTarget } from '../../components/codex-reset-credit' + type ProviderKey +} from '../../accounts/usage/usage-selectors' +import type { AccountsSnapshot, ProviderRateLimits } from '../../accounts/accounts-snapshot' +import { getActiveCodexAccountIdForRateLimitTarget } from '../../accounts/usage/codex-reset-credit' export type HomeUsageCard = { /** The managed account's id, or null for the agent's own login (System default). */ diff --git a/mobile/src/home/use-home-spare-page.ts b/mobile/src/home/use-home-spare-page.ts index 14a883477e1..2a8227e88c9 100644 --- a/mobile/src/home/use-home-spare-page.ts +++ b/mobile/src/home/use-home-spare-page.ts @@ -8,7 +8,7 @@ import { leaveHomeSparePage, prepareHomeSparePage } from '../mobile-web-shell/home-spare-page' -import { processGenerationStore } from '../mobile-web-shell/process-generation-store' +import { processGenerationStore } from '../mobile-web-shell/generations/process-generation-store' // Past Home's first paint and its first reads, so the boot never competes with them. const HOME_SPARE_IDLE_MS = 1000 diff --git a/mobile/src/home/use-mobile-home-data.ts b/mobile/src/home/use-mobile-home-data.ts index a0500640fed..86db717735c 100644 --- a/mobile/src/home/use-mobile-home-data.ts +++ b/mobile/src/home/use-mobile-home-data.ts @@ -16,7 +16,7 @@ import { } from '../agents/agent-list-rows' import { useAgentActivityWrites } from '../agents/use-agent-activity-writes' import { accountsSnapshotOptions } from '../accounts/accounts-snapshot-stream' -import type { AccountsSnapshot } from '../components/AccountUsage' +import type { AccountsSnapshot } from '../accounts/accounts-snapshot' import { HOST_LIST_TARGET, homeWorktreeCountsKey, diff --git a/mobile/src/host-catalog/host-removal-lifecycle.ts b/mobile/src/host-catalog/host-removal-lifecycle.ts index 65ff0eff370..29e05398f23 100644 --- a/mobile/src/host-catalog/host-removal-lifecycle.ts +++ b/mobile/src/host-catalog/host-removal-lifecycle.ts @@ -3,7 +3,7 @@ import { wipeHostStore } from '../device-store/device-store' import { deleteHostPageCache, forgetHostUpdateFailures -} from '../mobile-web-shell/removed-host-shell-cache' +} from '../mobile-web-shell/generations/removed-host-shell-cache' import { unregisterPushForRemovedHost } from '../notifications/push-registration' import { forgetNativeHostQueries } from '../query/native-query-persistence' import { forgetHostDescriptor } from '../host-descriptors/host-descriptor-store' diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index f14faed6778..cac5f2aa90f 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -820,6 +820,8 @@ "webShell": { "shellStateScreen": { "isolationUnavailable": "This device's WebView is too old to open the workspace safely.", + "isolationUnavailableAndroid": "Orca needs Android System WebView or Chrome 101 or newer. Update it from the Play Store, or pick a newer one in Developer options > WebView implementation.", + "webViewInUse": "This device has {{name}} {{version}}.", "downloadFailed": "The latest app could not be downloaded from this host.", "hostProfileUnreadable": "Could not read this host on your device. Try again.", "statusUnreadable": "Could not read this host's status. Go back and reopen it.", diff --git a/mobile/src/i18n/page-locale-catalog-source.test.ts b/mobile/src/i18n/page-locale-catalog-source.test.ts index d69a92dc1b2..98d2ab77a1a 100644 --- a/mobile/src/i18n/page-locale-catalog-source.test.ts +++ b/mobile/src/i18n/page-locale-catalog-source.test.ts @@ -204,15 +204,4 @@ describe('the page language catalog', () => { expect(i18n.getMobileUiLocale()).toBe('ko') expect(i18n.translate('greeting', 'Hello')).toBe('안녕하세요') }) - - it('imports the chunk an older shell left on disk, with no wait and no request', async () => { - chunksOnDisk.set('es', { greeting: 'Hola' }) - const client = fakeClient('reconnecting') - openPage(client, fakeStore({})) - - await i18n.activateMobileUiLocale('es') - - expect(i18n.translate('greeting', 'Hello')).toBe('Hola') - expect(client.sent).toHaveLength(0) - }) }) diff --git a/mobile/src/mobile-web-shell/ShellStateScreen.tsx b/mobile/src/mobile-web-shell/ShellStateScreen.tsx index d22e7e2c055..bc9d7ccaa91 100644 --- a/mobile/src/mobile-web-shell/ShellStateScreen.tsx +++ b/mobile/src/mobile-web-shell/ShellStateScreen.tsx @@ -1,5 +1,6 @@ import type { ReactNode } from 'react' -import { Pressable, Text, View } from 'react-native' +import { Platform, Pressable, Text, View } from 'react-native' +import { currentWebViewProvider } from '../../modules/orca-mobile-web-shell/src' import { ProtocolBlockScreen } from '../components/ProtocolBlockScreen' import { colors, radii, spacing, typography } from '../theme/mobile-theme' import { themedStyleSheet } from '../theme/themed-styles' @@ -65,11 +66,30 @@ function Failed({ useMobileColorScheme() // Retry cannot change a settled isolation gate or give an unsupported WebView the missing fence. const retryable = state.reason !== 'isolation-unavailable' && state.reason !== 'status-unreadable' + const provider = state.reason === 'isolation-unavailable' ? currentWebViewProvider() : null + // Unknown provider (older binary): a missing feature is still the likely cause. + const webViewTooOld = + Platform.OS === 'android' && + state.reason === 'isolation-unavailable' && + provider?.hasShellFeatures !== true return ( - {failureMessage(state.reason, t)} + {webViewTooOld + ? t( + 'webShell.shellStateScreen.isolationUnavailableAndroid', + 'Orca needs Android System WebView or Chrome 101 or newer. Update it from the Play Store, or pick a newer one in Developer options > WebView implementation.' + ) + : failureMessage(state.reason, t)} + {webViewTooOld && provider ? ( + + {t('webShell.shellStateScreen.webViewInUse', 'This device has {{name}} {{version}}.', { + name: provider.name, + version: provider.version + })} + + ) : null} {retryable ? ( [styles.retryButton, pressed && styles.pressed]} @@ -160,6 +180,12 @@ const styles = themedStyleSheet(() => ({ textAlign: 'center', marginBottom: spacing.lg }, + failedDetail: { + fontSize: typography.metaSize, + color: colors.textSecondary, + textAlign: 'center', + marginBottom: spacing.lg + }, retryButton: { backgroundColor: colors.bgRaised, paddingVertical: spacing.sm + 2, diff --git a/mobile/src/mobile-web-shell/generation-store.test.ts b/mobile/src/mobile-web-shell/generation-store.test.ts deleted file mode 100644 index 7b5ebd20edf..00000000000 --- a/mobile/src/mobile-web-shell/generation-store.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createGenerationStore } from './generation-store' -import { deriveHostCacheKey } from './host-cache-key' -import type { MobileWebBundleFetchResult } from '../transport/web-bundle/mobile-web-bundle-fetch' -import { computeMobileWebBundleId } from '../../../src/shared/mobile-web-bundle/manifest-contract' -import { - createFakeGenerationFileSystem as createFakeFileSystem, - FAKE_GENERATION_ROOT -} from './generation-file-system-fake' - -const ROOT = FAKE_GENERATION_ROOT -const HOST = deriveHostCacheKey('host-a') - -function buildResult(options: { - buildId?: string - assets?: readonly { path: string; byteLength: number; kind?: string }[] - bytes?: ReadonlyMap -}): MobileWebBundleFetchResult { - const listed = options.assets ?? [ - { path: 'index.html', byteLength: 4 }, - { path: 'assets/app.js', byteLength: 2 } - ] - const assets = listed.map((asset, index) => ({ - path: asset.path, - sha256: String(index).repeat(64).slice(0, 64), - byteLength: asset.byteLength, - contentType: 'text/html; charset=utf-8', - ...(asset.kind === undefined ? {} : { kind: asset.kind }) - })) - const totalBytes = assets.reduce((sum, asset) => sum + asset.byteLength, 0) - return { - manifest: { - schemaVersion: 1, - buildId: options.buildId ?? computeMobileWebBundleId(assets), - minCompatibleRuntimeProtocolVersion: 2, - runtimeProtocolVersion: 2, - entrypoint: 'index.html', - totalBytes, - assets - }, - assets: - options.bytes ?? - new Map(assets.map((asset) => [asset.path, new Uint8Array(asset.byteLength).fill(7)])), - reused: [], - totalBytes, - elapsedMs: 1 - } -} - -// Derive ids from assets so the cached manifest passes its digest check. -const BUILD = buildResult({}).manifest.buildId -const SECOND = { assets: [{ path: 'index.html', byteLength: 8 }] } -const SECOND_BUILD = buildResult(SECOND).manifest.buildId - -async function activate( - store: ReturnType, - hostKey: string, - result = buildResult({}) -): Promise { - await store.commitGeneration(await store.stageGeneration(hostKey, result)) -} - -// Commit deletes the old build first, so it must not run under a page still loading that build's chunks. -describe('an update staged behind a live page', () => { - it('stays staged while a page reads the old build, and the next read after it commits', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - await activate(store, HOST) - const release = store.holdGeneration(HOST) - store.deferCommit(await store.stageGeneration(HOST, buildResult(SECOND))) - - expect((await store.readActiveGeneration(HOST))?.buildId).toBe(BUILD) - expect(await fs.fileExists(`${ROOT}/${HOST}/generations/${BUILD}/index.html`)).toBe(true) - - release() - expect((await store.readActiveGeneration(HOST))?.buildId).toBe(SECOND_BUILD) - expect(await fs.fileExists(`${ROOT}/${HOST}/generations/${BUILD}/index.html`)).toBe(false) - }) - - it('stages a build without its language-catalog chunks and still commits it at the next launch', async () => { - const fs = createFakeFileSystem() - const first = createGenerationStore({ fileSystem: fs }) - await activate(first, HOST) - first.holdGeneration(HOST) - const withCatalog = buildResult({ - assets: [ - { path: 'index.html', byteLength: 8 }, - { path: 'assets/de.js', byteLength: 3, kind: 'catalog' } - ], - bytes: new Map([['index.html', new Uint8Array(8)]]) - }) - first.deferCommit(await first.stageGeneration(HOST, withCatalog)) - - const relaunched = createGenerationStore({ fileSystem: fs }) - - const build = withCatalog.manifest.buildId - expect((await relaunched.readActiveGeneration(HOST))?.buildId).toBe(build) - expect(await fs.fileExists(`${ROOT}/${HOST}/generations/${build}/assets/de.js`)).toBe(false) - }) -}) diff --git a/mobile/src/mobile-web-shell/generation-asset-path.ts b/mobile/src/mobile-web-shell/generations/generation-asset-path.ts similarity index 100% rename from mobile/src/mobile-web-shell/generation-asset-path.ts rename to mobile/src/mobile-web-shell/generations/generation-asset-path.ts diff --git a/mobile/src/mobile-web-shell/generation-cache-uri.ts b/mobile/src/mobile-web-shell/generations/generation-cache-uri.ts similarity index 100% rename from mobile/src/mobile-web-shell/generation-cache-uri.ts rename to mobile/src/mobile-web-shell/generations/generation-cache-uri.ts diff --git a/mobile/src/mobile-web-shell/generation-deferred-commits.ts b/mobile/src/mobile-web-shell/generations/generation-deferred-commits.ts similarity index 100% rename from mobile/src/mobile-web-shell/generation-deferred-commits.ts rename to mobile/src/mobile-web-shell/generations/generation-deferred-commits.ts diff --git a/mobile/src/mobile-web-shell/generation-file-system-fake.ts b/mobile/src/mobile-web-shell/generations/generation-file-system-fake.ts similarity index 100% rename from mobile/src/mobile-web-shell/generation-file-system-fake.ts rename to mobile/src/mobile-web-shell/generations/generation-file-system-fake.ts diff --git a/mobile/src/mobile-web-shell/generation-host-directories.ts b/mobile/src/mobile-web-shell/generations/generation-host-directories.ts similarity index 100% rename from mobile/src/mobile-web-shell/generation-host-directories.ts rename to mobile/src/mobile-web-shell/generations/generation-host-directories.ts diff --git a/mobile/src/mobile-web-shell/generation-host-order.ts b/mobile/src/mobile-web-shell/generations/generation-host-order.ts similarity index 100% rename from mobile/src/mobile-web-shell/generation-host-order.ts rename to mobile/src/mobile-web-shell/generations/generation-host-order.ts diff --git a/mobile/src/mobile-web-shell/generation-legacy-root.ts b/mobile/src/mobile-web-shell/generations/generation-legacy-root.ts similarity index 100% rename from mobile/src/mobile-web-shell/generation-legacy-root.ts rename to mobile/src/mobile-web-shell/generations/generation-legacy-root.ts diff --git a/mobile/src/mobile-web-shell/generation-manifest-read.ts b/mobile/src/mobile-web-shell/generations/generation-manifest-read.ts similarity index 97% rename from mobile/src/mobile-web-shell/generation-manifest-read.ts rename to mobile/src/mobile-web-shell/generations/generation-manifest-read.ts index 71c6ee09e18..22b768876d0 100644 --- a/mobile/src/mobile-web-shell/generation-manifest-read.ts +++ b/mobile/src/mobile-web-shell/generations/generation-manifest-read.ts @@ -2,7 +2,7 @@ import { MobileWebBundleManifestReadSchema, shellDownloadedAssets, type MobileWebBundleManifestRead -} from '../transport/web-bundle/mobile-web-bundle-reply-schemas' +} from '../../transport/web-bundle/mobile-web-bundle-reply-schemas' import { MANIFEST_FILE_NAME } from './generation-asset-path' import { joinUri } from './generation-cache-uri' import { parseJson } from './generation-host-order' diff --git a/mobile/src/mobile-web-shell/generation-reuse.ts b/mobile/src/mobile-web-shell/generations/generation-reuse.ts similarity index 94% rename from mobile/src/mobile-web-shell/generation-reuse.ts rename to mobile/src/mobile-web-shell/generations/generation-reuse.ts index f7eb4b257f2..45ca906afa5 100644 --- a/mobile/src/mobile-web-shell/generation-reuse.ts +++ b/mobile/src/mobile-web-shell/generations/generation-reuse.ts @@ -1,5 +1,5 @@ -import type { MobileWebBundleReusableAssets } from '../transport/web-bundle/mobile-web-bundle-fetch' -import type { MobileWebBundleAssetRead } from '../transport/web-bundle/mobile-web-bundle-reply-schemas' +import type { MobileWebBundleReusableAssets } from '../../transport/web-bundle/mobile-web-bundle-fetch' +import type { MobileWebBundleAssetRead } from '../../transport/web-bundle/mobile-web-bundle-reply-schemas' import { requireStorablePath } from './generation-asset-path' import { joinUri } from './generation-cache-uri' import type { ActiveGeneration } from './generation-store' diff --git a/mobile/src/mobile-web-shell/generation-staging-assets.ts b/mobile/src/mobile-web-shell/generations/generation-staging-assets.ts similarity index 82% rename from mobile/src/mobile-web-shell/generation-staging-assets.ts rename to mobile/src/mobile-web-shell/generations/generation-staging-assets.ts index cd61866c2b4..d8a083ba353 100644 --- a/mobile/src/mobile-web-shell/generation-staging-assets.ts +++ b/mobile/src/mobile-web-shell/generations/generation-staging-assets.ts @@ -1,5 +1,5 @@ -import type { MobileWebBundleFetchResult } from '../transport/web-bundle/mobile-web-bundle-fetch' -import { shellDownloadedAssets } from '../transport/web-bundle/mobile-web-bundle-reply-schemas' +import type { MobileWebBundleFetchResult } from '../../transport/web-bundle/mobile-web-bundle-fetch' +import { shellDownloadedAssets } from '../../transport/web-bundle/mobile-web-bundle-reply-schemas' import { requireStorablePath } from './generation-asset-path' import { joinUri } from './generation-cache-uri' diff --git a/mobile/src/mobile-web-shell/generation-store-file-system.test.ts b/mobile/src/mobile-web-shell/generations/generation-store-file-system.test.ts similarity index 89% rename from mobile/src/mobile-web-shell/generation-store-file-system.test.ts rename to mobile/src/mobile-web-shell/generations/generation-store-file-system.test.ts index 7b170ea268f..644f2c83d96 100644 --- a/mobile/src/mobile-web-shell/generation-store-file-system.test.ts +++ b/mobile/src/mobile-web-shell/generations/generation-store-file-system.test.ts @@ -1,11 +1,12 @@ import { describe, expect, it, vi } from 'vitest' -// Mock the import-time native module to test only the URI converter. +// Mock the import-time native modules to test only the URI converter. vi.mock('expo-file-system', () => ({ Directory: class {}, File: class {}, Paths: { cache: '' } })) +vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) import { generationDirectoryPath } from './generation-store-file-system' diff --git a/mobile/src/mobile-web-shell/generation-store-file-system.ts b/mobile/src/mobile-web-shell/generations/generation-store-file-system.ts similarity index 88% rename from mobile/src/mobile-web-shell/generation-store-file-system.ts rename to mobile/src/mobile-web-shell/generations/generation-store-file-system.ts index 74189aeb408..06aa62f880e 100644 --- a/mobile/src/mobile-web-shell/generation-store-file-system.ts +++ b/mobile/src/mobile-web-shell/generations/generation-store-file-system.ts @@ -1,4 +1,5 @@ import { Directory, File } from 'expo-file-system' +import { Platform } from 'react-native' export type GenerationDirectoryEntry = { readonly name: string @@ -127,7 +128,23 @@ export function createExpoGenerationFileSystem(rootUri: string): GenerationFileS } }, async moveDirectory(fromUri, toUri) { - new Directory(fromUri).move(new Directory(toUri)) + const from = new Directory(fromUri) + // Below API 26, Expo 55's move copies a directory without its contents; its copy is recursive. + if (Platform.OS === 'android' && Number(Platform.Version) < 26) { + const to = new Directory(toUri) + try { + from.copy(to) + } catch (error) { + // Readers trust a generation by its manifest, so a failed copy must leave no partial tree. + if (to.exists) { + to.delete() + } + throw error + } + from.delete() + return + } + from.move(new Directory(toUri)) }, async moveFile(fromUri, toUri) { new File(fromUri).move(new File(toUri)) diff --git a/mobile/src/mobile-web-shell/generation-store.ts b/mobile/src/mobile-web-shell/generations/generation-store.ts similarity index 96% rename from mobile/src/mobile-web-shell/generation-store.ts rename to mobile/src/mobile-web-shell/generations/generation-store.ts index 0e78ad2a2d6..c406de60e90 100644 --- a/mobile/src/mobile-web-shell/generation-store.ts +++ b/mobile/src/mobile-web-shell/generations/generation-store.ts @@ -1,8 +1,8 @@ -import type { MobileWebBundleManifestRead } from '../transport/web-bundle/mobile-web-bundle-reply-schemas' +import type { MobileWebBundleManifestRead } from '../../transport/web-bundle/mobile-web-bundle-reply-schemas' import type { MobileWebBundleFetchResult, MobileWebBundleReusableAssets -} from '../transport/web-bundle/mobile-web-bundle-fetch' +} from '../../transport/web-bundle/mobile-web-bundle-fetch' import { joinUri } from './generation-cache-uri' import { createGenerationHostOrder, withHostLast } from './generation-host-order' import { createDeferredCommits } from './generation-deferred-commits' @@ -18,7 +18,7 @@ import { listGenerationHostDirectories } from './generation-host-directories' import { isHostCacheKey } from './host-cache-key' -import type { MobileWebShellUpdateFailure } from './mobile-web-shell-update-failure' +import type { MobileWebShellUpdateFailure } from '../mobile-web-shell-update-failure' import { forgetHostUpdateFailuresIn, readUpdateFailureLog, @@ -216,7 +216,7 @@ export function createGenerationStore(options: { manifest: staged.manifest } const entries = await fs.list(generations) - // A build-id directory alone proves nothing: pre-API-26 Android moves can leave it empty. Require its activation manifest before reusing it. + // A build-id directory alone proves nothing; require its activation manifest before reusing it. const existing = entries.find((entry) => entry.name === staged.buildId) if ( existing?.isDirectory === true && @@ -238,7 +238,7 @@ export function createGenerationStore(options: { } await fs.createDirectory(generations) await fs.moveDirectory(staged.directory, target) - // Below API 26, Expo Android FileSystemPath.kt moves directories via non-recursive copy/delete and can leave an empty target; failed source deletion leaves tmp for sweeping. + // Never activate a target without its manifest; a source left in tmp is swept. if (!(await fs.fileExists(joinUri(target, MANIFEST_FILE_NAME)))) { await fs.delete(target) throw new Error(`generation ${staged.buildId} did not carry its manifest through the rename`) diff --git a/mobile/src/mobile-web-shell/host-cache-key.ts b/mobile/src/mobile-web-shell/generations/host-cache-key.ts similarity index 100% rename from mobile/src/mobile-web-shell/host-cache-key.ts rename to mobile/src/mobile-web-shell/generations/host-cache-key.ts diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-update-failure-log.test.ts b/mobile/src/mobile-web-shell/generations/mobile-web-shell-update-failure-log.test.ts similarity index 56% rename from mobile/src/mobile-web-shell/mobile-web-shell-update-failure-log.test.ts rename to mobile/src/mobile-web-shell/generations/mobile-web-shell-update-failure-log.test.ts index cd783473a9d..e5a79038800 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-update-failure-log.test.ts +++ b/mobile/src/mobile-web-shell/generations/mobile-web-shell-update-failure-log.test.ts @@ -1,10 +1,9 @@ import { describe, expect, it } from 'vitest' -import { computeMobileWebBundleId } from '../../../src/shared/mobile-web-bundle/manifest-contract' -import type { MobileWebBundleFetchResult } from '../transport/web-bundle/mobile-web-bundle-fetch' + import { createFakeGenerationFileSystem } from './generation-file-system-fake' import { createGenerationStore } from './generation-store' -import { deriveHostCacheKey } from './host-cache-key' -import type { MobileWebShellUpdateFailure } from './mobile-web-shell-update-failure' + +import type { MobileWebShellUpdateFailure } from '../mobile-web-shell-update-failure' import { appendUpdateFailure } from './mobile-web-shell-update-failure-log' const LOG = 'update-failures.json' @@ -52,43 +51,6 @@ describe('the generation store keeps the log', () => { expect(fileSystem.text(LOG)).toBeNull() }) - it("outlives the host's own cache, which a recovery deletes", async () => { - const fileSystem = createFakeGenerationFileSystem() - const store = createGenerationStore({ fileSystem }) - const host = deriveHostCacheKey('host-1') - const assets = [ - { path: 'index.html', sha256: '1'.repeat(64), byteLength: 1, contentType: 'text/html' } - ] - const buildId = computeMobileWebBundleId(assets) - const bundle: MobileWebBundleFetchResult = { - manifest: { - schemaVersion: 1, - buildId, - minCompatibleRuntimeProtocolVersion: 2, - runtimeProtocolVersion: 2, - entrypoint: 'index.html', - totalBytes: 1, - assets - }, - assets: new Map([['index.html', new Uint8Array(1)]]), - reused: [], - totalBytes: 1, - elapsedMs: 1 - } - await store.commitGeneration(await store.stageGeneration(host, bundle)) - expect((await store.readActiveGeneration(host))?.buildId).toBe(buildId) - expect(fileSystem.paths()).toContain(`${host}/generations/${buildId}/manifest.json`) - expect(fileSystem.bytes(`${host}/generations/${buildId}/index.html`)).toEqual(new Uint8Array(1)) - const recorded = failure('host-1', 1) - await store.recordUpdateFailure(recorded) - await store.deleteHostCache(host) - expect(fileSystem.paths().some((path) => path === host || path.startsWith(`${host}/`))).toBe( - false - ) - expect(await store.readActiveGeneration(host)).toBeNull() - expect(await store.readUpdateFailures()).toEqual([recorded]) - }) - it('reads a corrupt log as empty and keeps the entries that still parse', async () => { const fileSystem = createFakeGenerationFileSystem() const store = createGenerationStore({ fileSystem }) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-update-failure-log.ts b/mobile/src/mobile-web-shell/generations/mobile-web-shell-update-failure-log.ts similarity index 96% rename from mobile/src/mobile-web-shell/mobile-web-shell-update-failure-log.ts rename to mobile/src/mobile-web-shell/generations/mobile-web-shell-update-failure-log.ts index 8e6bcab8b67..1b53f810efa 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-update-failure-log.ts +++ b/mobile/src/mobile-web-shell/generations/mobile-web-shell-update-failure-log.ts @@ -1,5 +1,5 @@ import { z } from 'zod' -import { MobileWebBundleErrorCodeSchema } from '../../../src/shared/mobile-web-bundle/bundle-rpc-contract' +import { MobileWebBundleErrorCodeSchema } from '../../../../src/shared/mobile-web-bundle/bundle-rpc-contract' import { joinUri } from './generation-cache-uri' import type { GenerationFileSystem } from './generation-store-file-system' import { @@ -7,7 +7,7 @@ import { MOBILE_WEB_SHELL_UPDATE_FAILURE_REASONS, MOBILE_WEB_SHELL_UPDATE_FAILURE_WALLS, type MobileWebShellUpdateFailure -} from './mobile-web-shell-update-failure' +} from '../mobile-web-shell-update-failure' // Keep enough history to distinguish one bad download from repeated failures without growing diagnostic storage. export const MAX_UPDATE_FAILURES_PER_HOST = 5 diff --git a/mobile/src/mobile-web-shell/process-generation-store.ts b/mobile/src/mobile-web-shell/generations/process-generation-store.ts similarity index 88% rename from mobile/src/mobile-web-shell/process-generation-store.ts rename to mobile/src/mobile-web-shell/generations/process-generation-store.ts index 144fe4bf4bc..d6c9bcc9391 100644 --- a/mobile/src/mobile-web-shell/process-generation-store.ts +++ b/mobile/src/mobile-web-shell/generations/process-generation-store.ts @@ -1,8 +1,8 @@ import { Directory, Paths } from 'expo-file-system' -import { generationStoreDirectory } from '../../modules/orca-mobile-web-shell/src/generation-store-directory' +import { generationStoreDirectory } from '../../../modules/orca-mobile-web-shell/src/generation-store-directory' import { createGenerationStore, type GenerationStore } from './generation-store' import { createExpoGenerationFileSystem } from './generation-store-file-system' -import { dropHomeSparePage } from './home-spare-page' +import { dropHomeSparePage } from '../home-spare-page' const GENERATION_STORE_DIRECTORY_NAME = 'mobile-web' diff --git a/mobile/src/mobile-web-shell/removed-host-shell-cache.ts b/mobile/src/mobile-web-shell/generations/removed-host-shell-cache.ts similarity index 100% rename from mobile/src/mobile-web-shell/removed-host-shell-cache.ts rename to mobile/src/mobile-web-shell/generations/removed-host-shell-cache.ts diff --git a/mobile/src/mobile-web-shell/home-spare-page.ts b/mobile/src/mobile-web-shell/home-spare-page.ts index bf93ad3d371..8124dfa1cd4 100644 --- a/mobile/src/mobile-web-shell/home-spare-page.ts +++ b/mobile/src/mobile-web-shell/home-spare-page.ts @@ -3,9 +3,9 @@ import { discardSpareDocument, prepareSpareDocument } from '../../modules/orca-mobile-web-shell/src/spare-document' -import type { GenerationStore } from './generation-store' -import { generationDirectoryPath } from './generation-store-file-system' -import { deriveHostCacheKey } from './host-cache-key' +import type { GenerationStore } from './generations/generation-store' +import { generationDirectoryPath } from './generations/generation-store-file-system' +import { deriveHostCacheKey } from './generations/host-cache-key' import { mintShellSessionId } from './shell-session-id' // A Home entry claims the spare about 0.2 s after the tap on a simulator; a native screen keeps it no longer. diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-runtime.ts b/mobile/src/mobile-web-shell/mobile-web-shell-runtime.ts index 44e53bfd614..13dcb5edd6e 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-runtime.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-runtime.ts @@ -1,6 +1,6 @@ import { BRIDGE_READY_RETRY_MAX_MS } from './bridge/bridge-client-init-handshake' -import type { GenerationStore } from './generation-store' -import { processGenerationStore } from './process-generation-store' +import type { GenerationStore } from './generations/generation-store' +import { processGenerationStore } from './generations/process-generation-store' import { setForegroundTimer } from './foreground-timer' import { claimHomeSparePage } from './home-spare-page' import { mintShellSessionId } from './shell-session-id' diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts index b023ae70955..b829980919f 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts @@ -7,6 +7,7 @@ const doubles = vi.hoisted(() => ({ })) vi.mock('expo-file-system', () => ({ Directory: class {}, File: class {}, Paths: { cache: '' } })) +vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) // The runner's deadlines live in the runtime module, whose foreground timer reads React Native's AppState. vi.mock('./foreground-timer', () => ({ setForegroundTimer: () => () => {} })) vi.mock('../transport/rpc/rpc-operation', () => ({ @@ -20,9 +21,9 @@ vi.mock('../transport/web-bundle/mobile-web-bundle-fetch', () => ({ import type { RpcClient } from '../transport/rpc/rpc-client-contract' import { computeMobileWebBundleId } from '../../../src/shared/mobile-web-bundle/manifest-contract' import type { MobileWebBundleFetchResult } from '../transport/web-bundle/mobile-web-bundle-fetch' -import { createGenerationStore, type GenerationStore } from './generation-store' -import { createFakeGenerationFileSystem } from './generation-file-system-fake' -import { deriveHostCacheKey } from './host-cache-key' +import { createGenerationStore, type GenerationStore } from './generations/generation-store' +import { createFakeGenerationFileSystem } from './generations/generation-file-system-fake' +import { deriveHostCacheKey } from './generations/host-cache-key' import { download } from './mobile-web-shell-session-effects' const CLIENT: RpcClient = { @@ -114,64 +115,6 @@ describe('a download that reuses the cached generation', () => { return done.then(() => events) } - it('writes no staging bytes when canceled while its staging waits in the store queue', async () => { - const fileSystem = createFakeGenerationFileSystem() - const store = createGenerationStore({ fileSystem }) - const NEXT = bundle(16) - const BLOCKER = deriveHostCacheKey('host-b') - let enterBlocker = (): void => {} - const blockerEntered = new Promise((resolve) => { - enterBlocker = resolve - }) - let releaseBlocker = (): void => {} - const blockerReleased = new Promise((resolve) => { - releaseBlocker = resolve - }) - const list = fileSystem.list.bind(fileSystem) - fileSystem.list = async (uri) => { - if (uri.includes(`/${BLOCKER}/`)) { - enterBlocker() - await blockerReleased - } - return list(uri) - } - const writes: string[] = [] - const writeBytes = fileSystem.writeBytes.bind(fileSystem) - fileSystem.writeBytes = async (uri, bytes) => { - writes.push(uri) - await writeBytes(uri, bytes) - } - let blocker: Promise = Promise.resolve() - doubles.fetch = async () => { - blocker = store.readActiveGeneration(BLOCKER) - await blockerEntered - return NEXT - } - let markQueued = (): void => {} - const stageQueued = new Promise((resolve) => { - markQueued = resolve - }) - const downloads = new Set() - const run = runFor( - { - ...store, - stageGeneration: (...args) => { - const staged = store.stageGeneration(...args) - markQueued() - return staged - } - }, - downloads - ) - - await stageQueued - downloads.forEach((controller) => controller.abort()) - releaseBlocker() - await Promise.all([run, blocker]) - - expect(writes.filter((uri) => uri.includes(`/tmp/${NEXT.manifest.buildId}/`))).toEqual([]) - }) - it('stages from the offered snapshot without reopening its manifest after fetch', async () => { const { fileSystem, store } = await cachedStore() doubles.fetch = async () => { diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts index a8d939a15d7..257e9af5ad1 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts @@ -9,14 +9,14 @@ import { import type { MobileWebBundleCompatManifest } from '../transport/web-bundle/mobile-web-bundle-compat' import { runRpcOperation } from '../transport/rpc/rpc-operation' import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import type { GenerationStore, StagedGeneration } from './generation-store' +import type { GenerationStore, StagedGeneration } from './generations/generation-store' import type { createShellPageDeadline } from './shell-page-deadline' import { DOCUMENT_LOAD_DEADLINE_MS, PAGE_READY_DEADLINE_MS, type MobileWebShellRuntime } from './mobile-web-shell-runtime' -import { generationDirectoryPath } from './generation-store-file-system' +import { generationDirectoryPath } from './generations/generation-store-file-system' import type { CachedGeneration, MobileWebShellSessionEffect, diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts index c5b70b1822f..1ff5d92c198 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts @@ -7,7 +7,11 @@ import type { MobileWebBundleFetchResult } from '../transport/web-bundle/mobile-web-bundle-fetch' import type { MobileWebBundleManifestRead } from '../transport/web-bundle/mobile-web-bundle-reply-schemas' -import type { ActiveGeneration, GenerationStore, StagedGeneration } from './generation-store' +import type { + ActiveGeneration, + GenerationStore, + StagedGeneration +} from './generations/generation-store' import type { DownloadProgressFeed } from './download-progress-feed' import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract' import '../transport/rpc/rpc-delivery-ambiguity' @@ -205,7 +209,6 @@ function createFakeStore(): { } } -// Use recorded timers so deadline tests assert requested delays without wall-clock waits. type ArmedTimer = { delayMs: number; run: () => void; cancelled: boolean } function createTimerSeam() { @@ -347,7 +350,6 @@ async function flush(): Promise { await act(async () => undefined) } -// Entry import failures can finish WebView load without mounting a boundary or sending ready; the deadline must recover that silent blank page. describe('the wait for the page to speak', () => { beforeEach(() => { doubles.manifestReads = 0 @@ -358,24 +360,6 @@ describe('the wait for the page to speak', () => { doubles.gates.hostCapabilities = [MOBILE_WEB_BUNDLE_CAPABILITY] }) - async function ready(fake = createFakeStore()): Promise { - const mounted = await mount(fake.store) - fake.settleCacheRead(activeGeneration()) - await flush() - expect(mounted.states().at(-1)?.kind).toBe('ready') - return mounted - } - - // A remount mints the replacement's session before React commits it; reports the retired view already queued must not land on it. - it('does not charge a second fault from the retired view to its replacement', async () => { - const mounted = await ready() - await act(async () => { - mounted.shellFailed('document-load-failed') - mounted.shellFailed('document-load-failed') - }) - expect(mounted.states().at(-1)?.kind).toBe('ready') - }) - it('opens a page Home booted under its session id, and remounts under a fresh one', async () => { const fake = createFakeStore() const mounted = await mount(fake.store, undefined, async () => 'home-spare') @@ -389,21 +373,6 @@ describe('the wait for the page to speak', () => { expect(mounted.states().at(-1)).toMatchObject({ kind: 'ready', sessionId: 'session-1' }) }) - it('stays ready when the page speaks after document load and the timers fire', async () => { - const mounted = await ready() - await act(async () => { - mounted.documentLoaded() - mounted.pageReady() - }) - await act(async () => { - mounted.timers.fire() - }) - expect(mounted.states().at(-1)?.kind).toBe('ready') - await act(async () => { - mounted.tree.unmount() - }) - }) - it('re-arms a session the route rebuilt, with the host and its gates unchanged', async () => { // A route change rebuilds the session too; re-arm gates even if their verdict did not change. const fake = createFakeStore() @@ -454,5 +423,3 @@ describe('the wait for the page to speak', () => { }) }) }) - -// RN holds timers while backgrounded and fires overdue ones on resume, before the suspended WebView has loaded anything. diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.ts index ab448fb5e17..9c85c0aa08c 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.ts @@ -6,8 +6,8 @@ import { downloadFraction, type DownloadProgressFeed } from './download-progress-feed' -import type { GenerationStore } from './generation-store' -import { deriveHostCacheKey } from './host-cache-key' +import type { GenerationStore } from './generations/generation-store' +import { deriveHostCacheKey } from './generations/host-cache-key' import { runShellEffect, type FlowManifest } from './mobile-web-shell-session-effects' import { documentMayTalk } from './mobile-web-shell-gates' import { readMobileWebShellReachability } from './mobile-web-shell-reachability' diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-send-error.test.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-send-error.test.ts index 825c6960288..77871ebd73d 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-send-error.test.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-send-error.test.ts @@ -76,18 +76,6 @@ describe('useMobileNativeChatSendError', () => { expect(api().message).toBeNull() }) - it('a refusal behind a question goes once it is answered', async () => { - await render() - await showing({ working: false, prompt: true }) - await act(async () => - api().show("Answer the agent's question or approval, then run /clear.", { - refusedWhile: 'prompt' - }) - ) - await showing({ working: false, prompt: false }) - expect(api().message).toBeNull() - }) - it('a failure naming nothing the phone shows, or background tasks it cannot see, stays', async () => { await render() await act(async () => api().show('Message not sent')) @@ -115,16 +103,6 @@ describe('useMobileNativeChatSendError', () => { expect(api().message).toBeNull() }) - it('falls back to the toast when the banner is not mounted', async () => { - await act(async () => { - renderer = create(createElement(Harness, { scopeKey: 'terminal-1', bannerMounted: false })) - }) - await act(async () => api().show('Delivery unconfirmed')) - - expect(showToast).toHaveBeenCalledWith('Delivery unconfirmed', 1600) - expect(api().message).toBeNull() - }) - it('toasts a deferred failure that resolves after the user switched tabs', async () => { await render('terminal-1') const showFromTabA = api().show diff --git a/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.test.ts b/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.test.ts index 7c813e1409e..df00001b2a9 100644 --- a/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.test.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.test.ts @@ -342,33 +342,6 @@ it('phone captures accepted echoed inputs, preserves false, and freezes empty vs await harness.unmount() }) -it('accepts a typed literal at an attached fence while options refresh with no menu', async () => { - const pending = deferred() - let reads = 0 - const client = optionsClient(() => - ++reads === 1 ? Promise.resolve({ models: [], current: {} }) : pending.promise - ) - const { calls, mutate } = recordingMutate(async () => - accepted({ key: 'model', value: 'literal', options: { model: 'literal' } }, true) - ) - const view = await mountOptions({ ...BASE, client: client.client, mutate }) - await view.rerender({ fence: 2 }) - let result = true - await act(async () => { - result = await view.current().setStructuredOption('model', 'literal') - }) - expect(result).toBe(true) - expect(calls).toHaveLength(1) - await act(async () => pending.resolve({ models: [], current: {} })) - await settle() - await act(async () => { - result = await view.current().setStructuredOption('model', 'literal') - }) - expect(result).toBe(true) - expect(calls).toHaveLength(2) - await view.unmount() -}) - it('refreshes saved planning intent from the same host status stamp without remounting', async () => { let interactionMode: 'default' | 'plan' = 'default' const client = optionsClient(async () => ({ diff --git a/mobile/src/source-control/folder/use-folder-create-flow.test.tsx b/mobile/src/source-control/folder/use-folder-create-flow.test.tsx index c59d2644858..57360d9d270 100644 --- a/mobile/src/source-control/folder/use-folder-create-flow.test.tsx +++ b/mobile/src/source-control/folder/use-folder-create-flow.test.tsx @@ -243,15 +243,6 @@ describe('useFolderCreateFlow', () => { setupDecision: 'skip' }) }) - it("refreshes the folder when a form's create may have landed", async () => { - const refetch = vi.fn() - const { flow } = mountFlow(refetch) - const b = repoIn() - const form = await openComposer(flow, b) - - form.folderLaunch?.submit.begin({ ...b.repo, path: '/w/b' })?.settle('uncertain') - expect(refetch).toHaveBeenCalledTimes(1) - }) async function setupRefusedRetry(flow: { current: Flow | null }) { const a = repoIn() const lost = new FakeSession('connected') diff --git a/mobile/src/test-support/rpc-recording/adapters/codex-reset-credit-mount-adapters.ts b/mobile/src/test-support/rpc-recording/adapters/codex-reset-credit-mount-adapters.ts index 7f7c6d78df0..f1825228dcd 100644 --- a/mobile/src/test-support/rpc-recording/adapters/codex-reset-credit-mount-adapters.ts +++ b/mobile/src/test-support/rpc-recording/adapters/codex-reset-credit-mount-adapters.ts @@ -1,7 +1,9 @@ import { mountFixture } from '../recorder-fixture-shape' import type { operationModuleLoader } from '../operation-module-loader' import type { MountAdapter } from '../recording-scenario' -import type { AccountsSnapshot } from '../../../components/accounts-snapshot' +import type { AccountsSnapshot } from '../../../accounts/accounts-snapshot' +import type * as AccountsSnapshotModule from '../../../accounts/accounts-snapshot' +import type * as CodexResetCreditModule from '../../../accounts/usage/codex-reset-credit' const ACCOUNT_REVISION = 1_700_000_000_000 @@ -34,13 +36,11 @@ export function codexResetCreditMountAdapters( ): Record { return { 'accounts.codex-reset-credit': ({ client }) => { - const credit = modules.load( - 'mobile/src/components/codex-reset-credit.ts' + const credit = modules.load( + 'mobile/src/accounts/usage/codex-reset-credit.ts' ) const snapshot = modules - .load( - 'mobile/src/components/accounts-snapshot.ts' - ) + .load('mobile/src/accounts/accounts-snapshot.ts') .decodeAccountsSnapshot(CODEX_ACCOUNTS) let settled: unknown = null return { diff --git a/skill-guides/orca-cli.md b/skill-guides/orca-cli.md index fcedd851a73..cb89e0c74e5 100644 --- a/skill-guides/orca-cli.md +++ b/skill-guides/orca-cli.md @@ -28,9 +28,9 @@ Prefer `--json` for agent-driven calls. If the CLI is missing, say so explicitly A full handoff transfers ownership to another agent or worktree, then the original agent stops. Treat requests phrased as "hand off", "handoff", "handover", "give this to another agent", "give this to another worktree", "another agent", or "another worktree" as full handoffs unless the user expects the result back ("have another agent review this and report") or explicitly asks to supervise, monitor, wait for results, track completion, coordinate a DAG, use decision gates, or manage ask/reply. -A handoff is done when the new worktree id and agent handle have been reported and the prompt was delivered: the launch's `prompt.outcome` is `journaled` or `handed-to-terminal`, or, for an agent that was already running, the send receipt reported `accepted: true`. Do not wait for the receiving agent to finish. +A handoff is done when the new worktree id and agent handle have been reported and the prompt was delivered: the launch's `prompt.outcome` is `journaled` or `handed-to-terminal`, or, for an agent that was already running, the `terminal send` receipt reported `accepted: true` or `chat send` reported `delivery` `submitted` or `queued`. Do not wait for the receiving agent to finish. -Do not use `orca orchestration task-create`, `orca orchestration dispatch --inject`, or `orca orchestration check --wait` for full handoffs. `task-create` is also forbidden because it records coordinator-owned tracking state; if a task row is needed, the user asked for supervised orchestration. Deliver the prompt with the agent launch, or with terminal commands for an agent that is already running. +Do not use `orca orchestration task-create`, `orca orchestration dispatch --inject`, or `orca orchestration check --wait` for full handoffs. `task-create` is also forbidden because it records coordinator-owned tracking state; if a task row is needed, the user asked for supervised orchestration. Deliver the prompt with the agent launch, or with `terminal send` or `chat send` for an agent that is already running. For local work in the caller’s project, omit `--repo` and `--project`. Pass one to target another project or when Orca asks you to disambiguate; do not pick a repo from a list for unambiguous same-project work. The project comes from the caller’s directory, not the project visible in the app. Paired-server calls require an explicit server-side target. @@ -62,6 +62,14 @@ Existing-terminal handoff: ORCA terminal send --terminal --text "" --enter --json ``` +Existing-chat handoff, for an agent that runs as a chat (`outcome.kind` `structured`): + +```text +ORCA chat send --session --text "" --json +ORCA chat send --session --text "" --wait --timeout-ms 600000 --json +ORCA chat wait --session --timeout-ms 600000 --json +``` + ## Starting agents `worktree create --agent` (new checkout) and `agent launch` (existing worktree) are how to start an agent. They go through Orca's agent launch, the same one the app's new-agent tab uses: the user's Chat | CLI choice for that agent decides whether it opens as a chat or a terminal, and the result reports which (`outcome.kind`) and why (`receipt.detail`). When a chat is not possible, such as for an agent without chat support, the launch starts a terminal and the receipt says so. `--surface chat|terminal` picks one for that launch instead of the setting; pass it only when the user asked for a chat or a terminal. `--surface chat` is refused when Orca can establish before starting anything that the agent cannot open as a chat. If support cannot be checked, the launch can fall back to a terminal. If chat becomes unavailable only after a new workspace is created, Orca keeps that workspace, its setup and default tabs, then opens a terminal; the receipt explains the fallback. `terminal create` makes a terminal for shells and commands. @@ -273,6 +281,24 @@ Terminal rules: - For long output, use cursor reads. After a limited tail preview, page from `oldestCursor`; after a cursor read, continue with `nextCursor` while `limited` is true and `nextCursor !== latestCursor`. - `--direction vertical` splits left/right. `--direction horizontal` splits top/bottom. +## Chats + +Agents launched as chats are read and messaged with `chat`, not `terminal`. `chat list` names each chat's workspace, agent, state and last reply; `--session` takes the `session` it reports or the `handle` a launch returned. + +```text +ORCA chat list --json +ORCA chat list --state working --json +ORCA chat read --session --limit 10 --json +ORCA chat send --session --text "" --json +``` + +- `chat read` returns messages, tool calls, errors, and approvals or questions; `pending: true` marks one waiting for the user. +- `chat send` sends the text as the user's message. While the agent works, a host with a message queue holds it until the turn ends and reports `delivery: "queued"`. +- A refused send was not delivered. Read the chat again before resending. +- `chat send --wait` (or `chat wait`) returns when the chat settles, using `chat list` states: `settled: "done"`, or `"blocked"` on an approval or question, with the entries since the last user message; `settled: "timeout"` or `"held"` (queued message stopped or failed) exits 1. Pass `--timeout-ms`. Long or quoted text goes through `--text-file -` on stdin. +- Paired hosts can `chat list` only; read, send and wait run on the host machine. +- When relaying for a user from outside Orca (for example a voice or messaging assistant on the same machine), report from `chat list` and `chat read`, repeat an instruction back and get the user's confirmation before `chat send`, and send the user's words without adding instructions. + ## Artifacts diff --git a/skill-guides/orca-cli/references/browser.md b/skill-guides/orca-cli/references/browser.md index d10112b75f0..8e9564eab9a 100644 --- a/skill-guides/orca-cli/references/browser.md +++ b/skill-guides/orca-cli/references/browser.md @@ -71,6 +71,7 @@ Browser rules: - Pass `--page ` on every command that acts on one page; `ORCA --help` lists `--page` when it does. `tab list`, `tab current`, `tab create` and `open-url` take no `--page`, and `tab switch`/`tab close` pick a tab by `--index` or `--page`, never both, since `--page` wins. Take the ID from `result.tab.browserPageId` in `ORCA tab current --json` or `result.browserPageId` in `ORCA tab create --json` and keep it for the task; `tab current` shows the routed tab, not the one you pin. When the user means a specific tab, find it by URL or title in `ORCA tab list --json`. - Without `--page`, a command goes to the worktree's current tab. That stays the agent's tab while it has had a command in the last 20 seconds or so, even after the user picks another (`tab current` reports it too), then moves to the user's pick. - After `ORCA tab switch`, pass the new page's `browserPageId`. +- When the user says they left notes or comments on a page, read them with `ORCA tab annotations --page ` (the current tab without `--page`). It prints the notes they haven't sent, the same text the tab's Copy button gives, and `--json` returns them in `result.annotations`. Notes the user already sent arrive in your chat instead. - A popup window a page opens (sign-in, payment) is listed in `ORCA tab list --json` as a `popup-` page with `openerBrowserPageId`. If a click seems to do nothing, check `tab list`, then drive the popup with `--page popup-`. When it closes, continue on the opener page. - Browser commands default to the current worktree. `--page` reaches the page in any worktree unless you also pass `--worktree `. Use `--worktree all` only intentionally. - `tab list` shows every tab in the tab bar. After a restart, tabs the user has not opened report `loaded: false`; `tab switch` or any `--page` command loads one in the background without changing the user's visible tab. diff --git a/src/cli/browser/browser-format.ts b/src/cli/browser/browser-format.ts index 63a3d5d814f..ac3e7122022 100644 --- a/src/cli/browser/browser-format.ts +++ b/src/cli/browser/browser-format.ts @@ -1,10 +1,12 @@ import { readBrowserActionEffects } from '../../shared/browser-action-effects' import { writeCliScreenshotTempFile } from '../cli-screenshot-temp-file' import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' +import { formatBrowserAnnotationsAsMarkdown } from '../../shared/browser/annotations/browser-annotation-output' import type { BrowserProfileListResult, BrowserScreenshotResult, BrowserSnapshotResult, + BrowserTabAnnotationsResult, BrowserTabCurrentResult, BrowserTabListResult, BrowserTabProfileCloneResult, @@ -132,6 +134,13 @@ export function formatTabShow(result: BrowserTabShowResult | BrowserTabCurrentRe ].join('\n') } +// The same text the tab's Copy button gives, so an agent reads what the user would send. +export function formatTabAnnotations(result: BrowserTabAnnotationsResult): string { + return result.annotations.length > 0 + ? formatBrowserAnnotationsAsMarkdown(result.annotations) + : `No unsent notes on tab ${result.tab.browserPageId}` +} + export function formatTabProfileShow(result: BrowserTabProfileShowResult): string { return [ `page: ${result.browserPageId}`, diff --git a/src/cli/browser/browser-tab.ts b/src/cli/browser/browser-tab.ts index 74edfe04e53..7ee72d93664 100644 --- a/src/cli/browser/browser-tab.ts +++ b/src/cli/browser/browser-tab.ts @@ -1,11 +1,17 @@ import type { + BrowserTabAnnotationsResult, BrowserTabCurrentResult, BrowserTabListResult, BrowserTabShowResult, BrowserTabSwitchResult } from '../../shared/browser/runtime/runtime-browser-contracts' import type { CommandHandler } from '../dispatch' -import { formatTabList, formatTabListWithProfiles, formatTabShow } from './browser-format' +import { + formatTabAnnotations, + formatTabList, + formatTabListWithProfiles, + formatTabShow +} from './browser-format' import { printResult } from '../format' import { getOptionalNonNegativeIntegerFlag, @@ -42,6 +48,11 @@ export const BROWSER_TAB_HANDLERS: Record = { const result = await client.call('browser.tabShow', target) printResult(result, json, formatTabShow) }, + 'tab annotations': async ({ flags, client, cwd, json }) => { + const target = await getBrowserCommandTarget(flags, cwd, client) + const result = await client.call('browser.tabAnnotations', target) + printResult(result, json, formatTabAnnotations) + }, 'tab current': async ({ flags, client, cwd, json }) => { const worktree = await getBrowserWorktreeSelector(flags, cwd, client) const result = await client.call('browser.tabCurrent', { worktree }) diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index 6aaf42ad5c4..79d85aeda9d 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -256,9 +256,9 @@ const ORCA_CLI_MARKDOWN = [ "", "A full handoff transfers ownership to another agent or worktree, then the original agent stops. Treat requests phrased as \"hand off\", \"handoff\", \"handover\", \"give this to another agent\", \"give this to another worktree\", \"another agent\", or \"another worktree\" as full handoffs unless the user expects the result back (\"have another agent review this and report\") or explicitly asks to supervise, monitor, wait for results, track completion, coordinate a DAG, use decision gates, or manage ask/reply.", "", - "A handoff is done when the new worktree id and agent handle have been reported and the prompt was delivered: the launch's `prompt.outcome` is `journaled` or `handed-to-terminal`, or, for an agent that was already running, the send receipt reported `accepted: true`. Do not wait for the receiving agent to finish.", + "A handoff is done when the new worktree id and agent handle have been reported and the prompt was delivered: the launch's `prompt.outcome` is `journaled` or `handed-to-terminal`, or, for an agent that was already running, the `terminal send` receipt reported `accepted: true` or `chat send` reported `delivery` `submitted` or `queued`. Do not wait for the receiving agent to finish.", "", - "Do not use `orca orchestration task-create`, `orca orchestration dispatch --inject`, or `orca orchestration check --wait` for full handoffs. `task-create` is also forbidden because it records coordinator-owned tracking state; if a task row is needed, the user asked for supervised orchestration. Deliver the prompt with the agent launch, or with terminal commands for an agent that is already running.", + "Do not use `orca orchestration task-create`, `orca orchestration dispatch --inject`, or `orca orchestration check --wait` for full handoffs. `task-create` is also forbidden because it records coordinator-owned tracking state; if a task row is needed, the user asked for supervised orchestration. Deliver the prompt with the agent launch, or with `terminal send` or `chat send` for an agent that is already running.", "", "For local work in the caller’s project, omit `--repo` and `--project`. Pass one to target another project or when Orca asks you to disambiguate; do not pick a repo from a list for unambiguous same-project work. The project comes from the caller’s directory, not the project visible in the app. Paired-server calls require an explicit server-side target.", "", @@ -290,6 +290,14 @@ const ORCA_CLI_MARKDOWN = [ "ORCA terminal send --terminal --text \"\" --enter --json", "```", "", + "Existing-chat handoff, for an agent that runs as a chat (`outcome.kind` `structured`):", + "", + "```text", + "ORCA chat send --session --text \"\" --json", + "ORCA chat send --session --text \"\" --wait --timeout-ms 600000 --json", + "ORCA chat wait --session --timeout-ms 600000 --json", + "```", + "", "## Starting agents", "", "`worktree create --agent` (new checkout) and `agent launch` (existing worktree) are how to start an agent. They go through Orca's agent launch, the same one the app's new-agent tab uses: the user's Chat | CLI choice for that agent decides whether it opens as a chat or a terminal, and the result reports which (`outcome.kind`) and why (`receipt.detail`). When a chat is not possible, such as for an agent without chat support, the launch starts a terminal and the receipt says so. `--surface chat|terminal` picks one for that launch instead of the setting; pass it only when the user asked for a chat or a terminal. `--surface chat` is refused when Orca can establish before starting anything that the agent cannot open as a chat. If support cannot be checked, the launch can fall back to a terminal. If chat becomes unavailable only after a new workspace is created, Orca keeps that workspace, its setup and default tabs, then opens a terminal; the receipt explains the fallback. `terminal create` makes a terminal for shells and commands.", @@ -501,6 +509,24 @@ const ORCA_CLI_MARKDOWN = [ "- For long output, use cursor reads. After a limited tail preview, page from `oldestCursor`; after a cursor read, continue with `nextCursor` while `limited` is true and `nextCursor !== latestCursor`.", "- `--direction vertical` splits left/right. `--direction horizontal` splits top/bottom.", "", + "## Chats", + "", + "Agents launched as chats are read and messaged with `chat`, not `terminal`. `chat list` names each chat's workspace, agent, state and last reply; `--session` takes the `session` it reports or the `handle` a launch returned.", + "", + "```text", + "ORCA chat list --json", + "ORCA chat list --state working --json", + "ORCA chat read --session --limit 10 --json", + "ORCA chat send --session --text \"\" --json", + "```", + "", + "- `chat read` returns messages, tool calls, errors, and approvals or questions; `pending: true` marks one waiting for the user.", + "- `chat send` sends the text as the user's message. While the agent works, a host with a message queue holds it until the turn ends and reports `delivery: \"queued\"`.", + "- A refused send was not delivered. Read the chat again before resending.", + "- `chat send --wait` (or `chat wait`) returns when the chat settles, using `chat list` states: `settled: \"done\"`, or `\"blocked\"` on an approval or question, with the entries since the last user message; `settled: \"timeout\"` or `\"held\"` (queued message stopped or failed) exits 1. Pass `--timeout-ms`. Long or quoted text goes through `--text-file -` on stdin.", + "- Paired hosts can `chat list` only; read, send and wait run on the host machine.", + "- When relaying for a user from outside Orca (for example a voice or messaging assistant on the same machine), report from `chat list` and `chat read`, repeat an instruction back and get the user's confirmation before `chat send`, and send the user's words without adding instructions.", + "", "", "", "## Artifacts", @@ -740,6 +766,7 @@ const ORCA_CLI_BROWSER_REFERENCE_MARKDOWN = [ "- Pass `--page ` on every command that acts on one page; `ORCA --help` lists `--page` when it does. `tab list`, `tab current`, `tab create` and `open-url` take no `--page`, and `tab switch`/`tab close` pick a tab by `--index` or `--page`, never both, since `--page` wins. Take the ID from `result.tab.browserPageId` in `ORCA tab current --json` or `result.browserPageId` in `ORCA tab create --json` and keep it for the task; `tab current` shows the routed tab, not the one you pin. When the user means a specific tab, find it by URL or title in `ORCA tab list --json`.", "- Without `--page`, a command goes to the worktree's current tab. That stays the agent's tab while it has had a command in the last 20 seconds or so, even after the user picks another (`tab current` reports it too), then moves to the user's pick.", "- After `ORCA tab switch`, pass the new page's `browserPageId`.", + "- When the user says they left notes or comments on a page, read them with `ORCA tab annotations --page ` (the current tab without `--page`). It prints the notes they haven't sent, the same text the tab's Copy button gives, and `--json` returns them in `result.annotations`. Notes the user already sent arrive in your chat instead.", "- A popup window a page opens (sign-in, payment) is listed in `ORCA tab list --json` as a `popup-` page with `openerBrowserPageId`. If a click seems to do nothing, check `tab list`, then drive the popup with `--page popup-`. When it closes, continue on the opener page.", "- Browser commands default to the current worktree. `--page` reaches the page in any worktree unless you also pass `--worktree `. Use `--worktree all` only intentionally.", "- `tab list` shows every tab in the tab bar. After a restart, tabs the user has not opened report `loaded: false`; `tab switch` or any `--page` command loads one in the background without changing the user's visible tab.", diff --git a/src/cli/chat-history.ts b/src/cli/chat-history.ts new file mode 100644 index 00000000000..db4c70730cd --- /dev/null +++ b/src/cli/chat-history.ts @@ -0,0 +1,168 @@ +import type { + AgentSessionHistoryPage, + AgentSessionHistoryResult +} from '../shared/agent-session/agent-session-wire' +import { AGENT_SESSION_HISTORY_MAX_LIMIT } from '../shared/agent-session/agent-session-wire' +import { + AGENT_SESSION_UNATTACHED_REFUSAL_CODE, + isUnattachedAgentSessionReadRefusal +} from '../shared/agent-session/failures/structured-agent-session-read-refusal' +import { structuredAgentSessionQueueSendsNext } from '../shared/agent-session/view/structured-agent-session-live-turn' +import { chatTranscript, formatChatRead, type ChatTranscriptEntry } from './chat-sessions' +import type { RuntimeClient, RuntimeRpcSuccess } from './runtime-client' +import { RuntimeClientError } from './runtime-client' + +export const DEFAULT_READ_LIMIT = 20 +const WAIT_POLL_MS = 1000 + +export type ChatTranscript = { + session: string + entries: ChatTranscriptEntry[] + /** Newest journal row read, so a later `--since` can continue from it. */ + cursor: AgentSessionHistoryPage['window']['newest'] + /** Older rows exist that this 200-row read did not reach, and they were needed. */ + truncated: boolean +} +/** The chat's own turn in `chat list` words (structuredAgentSessionLeadState), plus two wait-only outcomes. */ +export type ChatSettled = 'done' | 'blocked' | 'held' | 'timeout' + +export async function readHistory( + client: RuntimeClient, + session: string, + limit: number +): Promise> { + return client + .call('agentSession.history', { + sessionId: session, + direction: 'tail', + limit + }) + .catch((error: unknown) => { + throw explainChatRefusal(error, session, 'read') + }) +} + +export async function readTranscript( + client: RuntimeClient, + session: string, + limit?: number +): Promise> { + // Status frames and turn markers share the journal, so read the most rows a page allows. + const response = await readHistory(client, session, AGENT_SESSION_HISTORY_MAX_LIMIT) + const { page } = response.result + const all = chatTranscript(page.items, page.actionablePromptIds) + const entries = limit === undefined ? all : all.slice(-limit) + const truncated = page.hasOlder && (limit === undefined || all.length < limit) + return { ...response, result: { session, entries, cursor: page.window.newest, truncated } } +} + +export function requireWorkingFlag(page: AgentSessionHistoryPage): void { + if (page.working === undefined) { + throw new RuntimeClientError( + 'incompatible_runtime', + 'This Orca host does not report when a chat is working, so it cannot wait. Update Orca on the host.' + ) + } +} + +// Settled means no running turn or unanswered send, or a question/approval waiting for the user. +export async function waitForChat( + client: RuntimeClient, + session: string, + timeoutMs: number | undefined, + queuedMessageId?: string +): Promise { + const deadline = timeoutMs === undefined ? Infinity : Date.now() + timeoutMs + for (;;) { + const { page } = (await readHistory(client, session, 1)).result + requireWorkingFlag(page) + if ((page.actionablePromptIds?.length ?? 0) > 0) { + return 'blocked' + } + // Between turns the host names its next automatic send while working is briefly false. + const sendsNext = structuredAgentSessionQueueSendsNext( + page.nextQueuedMessageId, + page.working === true + ) + if (!page.working && !sendsNext) { + // Still queued with nothing running or about to send: stopped, failed or held across a reopen. + const held = page.queuedMessages?.some((m) => m.messageId === queuedMessageId) === true + return held ? 'held' : 'done' + } + if (Date.now() >= deadline) { + return 'timeout' + } + await new Promise((resolve) => setTimeout(resolve, WAIT_POLL_MS)) + } +} + +// After a wait, the turn's entries: everything after the last user message. +export async function readSettledTurn( + client: RuntimeClient, + session: string, + settled: ChatSettled +): Promise> { + if (settled === 'timeout' || settled === 'held') { + // Chained commands such as `send --wait && ...` need a failing exit when the chat did not settle. + process.exitCode = 1 + } + const response = await readTranscript(client, session) + const { entries, truncated } = response.result + const lastUser = entries.findLastIndex((e) => e.kind === 'message' && e.role === 'user') + // A held message never ran, so the last turn on the page is not its reply. + const turn = settled === 'held' ? [] : entries.slice(lastUser + 1) + return { + ...response, + result: { + ...response.result, + entries: turn, + truncated: settled !== 'held' && truncated && lastUser === -1, + settled + } + } +} + +export function formatSettled(result: ChatTranscript & { settled: ChatSettled }): string { + const status = + result.settled === 'timeout' + ? 'Still working when the wait timed out.' + : result.settled === 'held' + ? 'Your message is held in the queue (the chat was stopped or the send failed). Resume it in Orca.' + : result.settled === 'blocked' + ? 'Blocked: waiting for you to answer an approval or question.' + : 'Done.' + return result.entries.length === 0 ? status : `${formatChatRead(result)}\n${status}` +} + +// The host answers with bare wire codes; say what they mean for this command. +export function explainChatRefusal( + error: unknown, + sessionId: string, + action: 'rename' | 'read' | 'send to' +): unknown { + if (!(error instanceof RuntimeClientError)) { + return error + } + if (error.message === 'agent_session_identity_required') { + return new RuntimeClientError( + 'agent_session_identity_required', + `No chat with session id ${sessionId} on this host.` + ) + } + if (isUnattachedAgentSessionReadRefusal(error)) { + return new RuntimeClientError( + AGENT_SESSION_UNATTACHED_REFUSAL_CODE, + `No open chat with session id ${sessionId} on this host. Find it with \`orca chat list\`.` + ) + } + if ( + error.message === 'structured_agent_session_unsupported' || + error.code === 'method_not_found' + ) { + return new RuntimeClientError( + 'incompatible_runtime', + `This Orca host cannot ${action} chats from the CLI. Update Orca on that host, or check that it has chats turned on.` + ) + } + return error +} diff --git a/src/cli/chat-sessions.ts b/src/cli/chat-sessions.ts new file mode 100644 index 00000000000..e88453284f6 --- /dev/null +++ b/src/cli/chat-sessions.ts @@ -0,0 +1,175 @@ +import { agentSessionPromptQuestions } from '../shared/agent-session/agent-session-question-answer' +import { isActionableStructuredAgentSessionPrompt } from '../shared/agent-session/view/structured-agent-session-live-turn' +import { isRootAgentJournalItem } from '../shared/agent-session/journal/agent-session-journal-producer' +import type { AgentJournalRenderItem } from '../shared/agent-session/journal/agent-session-journal-types' +import type { + RuntimeWorktreeAgentRow, + RuntimeWorktreePsSummary +} from '../shared/runtime-worktree-contracts' +import { structuredAgentSessionTabId } from '../shared/agent-session/view/structured-agent-session-projection' +import { RuntimeClientError } from './runtime-client' + +const CHAT_HANDLE_PREFIX = structuredAgentSessionTabId('') + +export type ChatSessionEntry = { + session: string + handle: string + worktreeId: string + worktree: string + agentType: string | null + state: RuntimeWorktreeAgentRow['state'] + title: string | null + lastAssistantMessage: string | null + updatedAt: number +} + +export type ChatTranscriptEntry = + | { kind: 'message'; role: string; text: string } + | { kind: 'tool'; name: string; state: string } + | { kind: 'approval' | 'question'; text: string; pending: boolean } + | { kind: 'error'; text: string } + +/** The session id a chat is addressed by, from its id, its handle, or a pane key that names it. */ +export function parseChatSessionSelector(value: string): string { + const withoutHandle = value.startsWith(CHAT_HANDLE_PREFIX) + ? value.slice(CHAT_HANDLE_PREFIX.length) + : value + // A pane key is the chat's handle and its leaf: ":". + const session = withoutHandle.split(':')[0]?.trim() ?? '' + if (session.length === 0) { + throw new RuntimeClientError( + 'invalid_argument', + '--session needs a chat session id or handle; run `orca chat list` to find one.' + ) + } + return session +} + +/** The top-level chats in a worktree summary. Terminal agents and subagents are left out: + * terminals are read with `orca terminal`, and a subagent is reached through its parent chat. */ +export function listChatSessions( + worktrees: readonly RuntimeWorktreePsSummary[] +): ChatSessionEntry[] { + return worktrees.flatMap((worktree) => + worktree.agents + .filter( + (agent) => agent.parentPaneKey === null && agent.paneKey.startsWith(CHAT_HANDLE_PREFIX) + ) + .map((agent) => { + const session = parseChatSessionSelector(agent.paneKey) + return { + session, + handle: structuredAgentSessionTabId(session), + worktreeId: worktree.worktreeId, + worktree: worktree.displayName, + agentType: agent.agentType, + state: agent.state, + title: agent.displayName ?? agent.taskTitle, + lastAssistantMessage: agent.lastAssistantMessage, + updatedAt: agent.updatedAt + } + }) + ) +} + +function messageText(item: AgentJournalRenderItem): string { + if (item.body.kind !== 'message') { + return '' + } + return item.body.blocks + .map((block) => + block.type === 'text' ? block.text : block.type === 'image-ref' ? '[image]' : '' + ) + .filter((text) => text.length > 0) + .join('\n') + .trim() +} + +/** The conversation as a reader follows it: messages, the tools the agent ran, and the + * approvals and questions it raised. Provider status frames and turn markers are left out. */ +export function chatTranscript( + items: readonly AgentJournalRenderItem[], + actionablePromptIds?: readonly string[] +): ChatTranscriptEntry[] { + // An ended agent's unanswered prompts stay pending in the journal but can no longer be answered. + const waiting = (item: AgentJournalRenderItem, state: string): boolean => + state === 'pending' && + isActionableStructuredAgentSessionPrompt(item.itemId, actionablePromptIds) + const entries: ChatTranscriptEntry[] = [] + for (const item of items) { + // Subagents share the journal; their rows belong to their own section, not the chat's turn. + if (!isRootAgentJournalItem(item)) { + continue + } + const body = item.body + if (body.kind === 'message') { + const text = messageText(item) + // Reasoning is the model's scratch work, folded away in the app too. + if (text.length > 0 && body.role !== 'reasoning') { + entries.push({ kind: 'message', role: body.role, text }) + } + } else if (body.kind === 'status' && body.tone === 'error') { + // Start failures and dead agents land as error status rows; without them a wait reads "Done.". + entries.push({ kind: 'error', text: String(body.text) }) + } else if (body.kind === 'tool-call') { + entries.push({ kind: 'tool', name: body.name, state: body.state }) + } else if (body.kind === 'approval') { + entries.push({ + kind: 'approval', + text: body.title, + pending: waiting(item, body.resolution.state) + }) + } else if (body.kind === 'question') { + entries.push({ + kind: 'question', + // Grouped prompts keep their real questions in `questions`; `question` is then a heading. + text: agentSessionPromptQuestions(body) + .map((q) => q.question) + .join('\n'), + pending: waiting(item, body.resolution.state) + }) + } + } + return entries +} + +export function formatChatList(result: { chats: ChatSessionEntry[] }): string { + if (result.chats.length === 0) { + return 'No chats.' + } + return result.chats + .map((chat) => + [ + `${chat.worktree} · ${chat.agentType ?? 'agent'} · ${chat.state}`, + ` session: ${chat.session}`, + ...(chat.title ? [` title: ${chat.title}`] : []), + ...(chat.lastAssistantMessage + ? [` last reply: ${chat.lastAssistantMessage.replace(/\s+/g, ' ').slice(0, 200)}`] + : []) + ].join('\n') + ) + .join('\n\n') +} + +export function formatChatRead(result: { + session: string + entries: ChatTranscriptEntry[] +}): string { + if (result.entries.length === 0) { + return `No messages in ${result.session}.` + } + return result.entries + .map((entry) => { + if (entry.kind === 'message') { + return `${entry.role}: ${entry.text}` + } + if (entry.kind === 'error') { + return `[error] ${entry.text}` + } + if (entry.kind === 'tool') { + return `[tool ${entry.name}: ${entry.state}]` + } + return `[${entry.kind}${entry.pending ? ', waiting for you' : ''}] ${entry.text}` + }) + .join('\n') +} diff --git a/src/cli/command-scoped-flag-help.ts b/src/cli/command-scoped-flag-help.ts index fc5c6c56006..92e83f0a753 100644 --- a/src/cli/command-scoped-flag-help.ts +++ b/src/cli/command-scoped-flag-help.ts @@ -2,7 +2,22 @@ const FILE_OPEN_FOCUS_HELP = "--focus Bring the user to the file (switches Orca's window to its worktree)" +const CHAT_SESSION_HELP = + '--session Chat session id or handle from chat list or agent launch' + const COMMAND_SCOPED_FLAG_HELP: Record> = { + 'chat rename': { + session: '--session Chat session id from chat list or agent launch' + }, + 'chat list': { + state: '--state Only chats in this state: working, blocked, waiting or done' + }, + 'chat read': { session: CHAT_SESSION_HELP }, + 'chat send': { + session: CHAT_SESSION_HELP, + wait: '--wait Wait until the chat finishes or needs your answer' + }, + 'chat wait': { session: CHAT_SESSION_HELP }, 'extension reload': { 'extension-id': '--extension-id Installed unpacked extension ID; also accepted positionally', diff --git a/src/cli/flag-help-text.ts b/src/cli/flag-help-text.ts index 108cf43bf8f..1e283dd828f 100644 --- a/src/cli/flag-help-text.ts +++ b/src/cli/flag-help-text.ts @@ -36,6 +36,7 @@ export const FLAG_HELP_TEXT: Record = { interrupt: '--interrupt Send as an interrupt-style input when supported', 'keep-open': '--keep-open Keep the worker open after it finishes', 'spec-file': '--spec-file Read the spec from a file or stdin', + 'text-file': '--text-file Read the text from a file or stdin', id: '--id Identifier for a target item or permission', issue: '--issue Linked GitHub issue number', 'gitlab-issue': diff --git a/src/cli/handler-group-manifest.ts b/src/cli/handler-group-manifest.ts index 9cc19bf9f86..31606226998 100644 --- a/src/cli/handler-group-manifest.ts +++ b/src/cli/handler-group-manifest.ts @@ -207,7 +207,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ }, { name: 'chat', - keys: ['chat rename'], + keys: ['chat rename', 'chat list', 'chat read', 'chat send', 'chat wait'], load: async () => (await import('./handlers/chat.js')).CHAT_HANDLERS }, { diff --git a/src/cli/handlers/chat.test.ts b/src/cli/handlers/chat.test.ts index 50005f098b6..177a839ad13 100644 --- a/src/cli/handlers/chat.test.ts +++ b/src/cli/handlers/chat.test.ts @@ -1,7 +1,183 @@ import { afterEach, describe, expect, it, vi } from 'vitest' +import { SendParams } from '../../shared/rpc-contract/structured-agent-session-params' +import { AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY } from '../../shared/agent-session/agent-session-runtime-capabilities' import { RuntimeClient } from '../runtime-client' import { CHAT_HANDLERS } from './chat' +const SESSION = 'codex_8eb631ab_59c5_41e4_8672_01cfe0a6fd5f' + +function ok(result: unknown) { + return { id: 'req', ok: true, result, _meta: { runtimeId: 'runtime-1' } } +} + +function historyPage( + items: unknown[], + fence: number | undefined = 3, + pageOverrides: Record = {} +) { + return ok({ + ok: true, + page: { + sessionId: SESSION, + epoch: 'e', + fence, + direction: 'tail', + items, + removedItemIds: [], + submissions: [], + window: { + oldest: null, + newest: { epoch: 'e', sequence: 9 }, + nextCursor: { epoch: 'e', sequence: 9 } + }, + ...pageOverrides + } + }) +} + +function item(body: unknown) { + return { itemId: 'i', revision: 1, sequence: 1, observedAt: 1, body } +} + +function fakeClient( + responses: unknown[], + capabilities: string[] = [AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY] +): RuntimeClient & { call: ReturnType } { + const client = new RuntimeClient('/tmp/orca-chat-test', 60_000, null, null) + const call = vi.fn() + for (const response of responses) { + call.mockResolvedValueOnce(response) + } + vi.spyOn(client, 'call').mockImplementation(call) + vi.spyOn(client, 'getCliStatus').mockResolvedValue({ + id: 'status', + ok: true, + result: { + app: { running: true, pid: 123 }, + runtime: { state: 'ready', reachable: true, runtimeId: 'runtime-1', capabilities }, + graph: { state: 'ready' } + }, + _meta: { runtimeId: 'runtime-1' } + }) + return Object.assign(client, { call }) +} + +async function run( + command: string, + flags: Record, + client: RuntimeClient +) { + const logs: string[] = [] + const spy = vi.spyOn(console, 'log').mockImplementation((line: string) => logs.push(line)) + try { + await CHAT_HANDLERS[command]!({ + flags: new Map(Object.entries(flags)), + client, + cwd: '/tmp', + json: true + }) + } finally { + spy.mockRestore() + } + return JSON.parse(logs.join('\n')).result +} + +afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() +}) + +describe('chat send', () => { + it('sends a host-valid message fenced to the chat it read, queued while the agent works', async () => { + const client = fakeClient([ + historyPage([], 7), + ok({ + ok: true, + replayed: false, + fence: 7, + cursor: { epoch: 'e', sequence: 2 }, + value: { + clientMessageId: 'm-1', + queued: { messageId: 'q-1', position: 1, state: 'waiting' } + } + }) + ]) + const result = await run('chat send', { session: SESSION, text: 'Run the tests' }, client) + const params = client.call.mock.calls[1]![1] + expect(client.call.mock.calls[1]![0]).toBe('agentSession.send') + // The host validates the same schema, so a malformed envelope or body fails here. + expect(SendParams.safeParse(params).success).toBe(true) + expect(params).toMatchObject({ + envelope: { sessionId: SESSION, expectedRuntimeFence: 7 }, + delivery: 'queue-if-active', + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Run the tests' }] } + }) + expect(result).toEqual({ + session: SESSION, + delivery: 'queued', + clientMessageId: 'm-1', + queuePosition: 1 + }) + }) + + it('reports a host refusal as an error instead of a sent message', async () => { + const client = fakeClient([ + historyPage([], 2), + ok({ + ok: false, + refusal: { code: 'agent_session_fence_mismatch', message: 'The chat restarted.' } + }) + ]) + await expect(run('chat send', { session: SESSION, text: 'hi' }, client)).rejects.toMatchObject({ + code: 'agent_session_fence_mismatch' + }) + }) + + it('with --wait, waits for its queued message to run and returns that turn', async () => { + vi.useFakeTimers() + const client = fakeClient([ + historyPage([], 7, { working: true }), + ok({ + ok: true, + replayed: false, + fence: 7, + cursor: { epoch: 'e', sequence: 2 }, + value: { + clientMessageId: 'm-1', + queued: { messageId: 'q-1', position: 1, state: 'waiting' } + } + }), + // The earlier turn ended, but the queued message has not been handed to the agent yet. + historyPage([], 7, { + working: false, + queuedMessages: [{ messageId: 'q-1' }], + nextQueuedMessageId: 'q-1' + }), + historyPage([], 7, { working: true, queuedMessages: [] }), + historyPage([], 7, { working: false, queuedMessages: [], actionablePromptIds: [] }), + historyPage([ + item({ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Earlier' }] }), + item({ kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Old reply' }] }), + item({ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Run the tests' }] }), + item({ kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'All pass' }] }) + ]) + ]) + const pending = run( + 'chat send', + { session: SESSION, text: 'Run the tests', wait: true }, + client + ) + await vi.advanceTimersByTimeAsync(5_000) + const result = await pending + expect(client.call).toHaveBeenCalledTimes(6) + expect(result).toMatchObject({ + delivery: 'queued', + settled: 'done', + entries: [{ kind: 'message', role: 'assistant', text: 'All pass' }] + }) + }) +}) + function chatClient(isRemote: boolean): { client: RuntimeClient; call: ReturnType } { const client = new RuntimeClient('/tmp/orca-chat-test', 60_000, null, null) vi.spyOn(client, 'isRemote', 'get').mockReturnValue(isRemote) diff --git a/src/cli/handlers/chat.ts b/src/cli/handlers/chat.ts index f9303026a8d..51d6a8dbc0f 100644 --- a/src/cli/handlers/chat.ts +++ b/src/cli/handlers/chat.ts @@ -1,11 +1,64 @@ -import type { CommandHandler } from '../dispatch' -import { getPresentStringFlag, getRequiredStringFlag } from '../flags' -import { printResult } from '../format' -import { RuntimeClientError } from '../runtime-client' +import { randomUUID } from 'node:crypto' +import type { + AgentSessionMutationResult, + AgentSessionSendResult +} from '../../shared/agent-session/agent-session-wire' +import { AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY } from '../../shared/agent-session/agent-session-runtime-capabilities' +import type { + RuntimeWorktreePsResult, + RuntimeWorktreeRecord +} from '../../shared/runtime-worktree-contracts' +import { createStructuredAgentSessionOperationId } from '../../shared/agent-session/lifecycle/structured-agent-session-mutation' +import { + structuredAgentSessionMessageSendMutation, + structuredAgentSessionSendBody +} from '../../shared/agent-session/requests/structured-agent-session-send-mutation' +import { AGENT_STATUS_STATES } from '../../shared/agent-status/contracts/agent-status-types' import { readInjectedAgentSessionId } from '../../shared/agent-session/lifecycle/agent-session-caller-env' +import { + DEFAULT_READ_LIMIT, + explainChatRefusal, + formatSettled, + readHistory, + readSettledTurn, + readTranscript, + requireWorkingFlag, + waitForChat +} from '../chat-history' +import { + formatChatList, + formatChatRead, + listChatSessions, + parseChatSessionSelector +} from '../chat-sessions' +import { readTextOrFileFlag } from '../command-body-input' +import type { CommandHandler } from '../dispatch' +import { + getOptionalPositiveIntegerFlag, + getOptionalStringFlag, + getPresentStringFlag, + getRequiredStringFlag +} from '../flags' +import { printResult } from '../format' +import { getOptionalWorktreeSelector } from '../selectors' +import type { RuntimeClient } from '../runtime-client' +import { RuntimeClientError } from '../runtime-client' + +const MAX_READ_LIMIT = 100 type ChatRenameResult = { name: string | null; applied: boolean } +// Paired CLIs lack the host's chat read/send capability; refuse before the host does with a bare code. +function readSession(flags: Map, client: RuntimeClient): string { + if (client.isRemote) { + throw new RuntimeClientError( + 'runtime_unsupported', + 'Reading and messaging chats on a paired host is not supported yet. Run this on the host machine.' + ) + } + return parseChatSessionSelector(getRequiredStringFlag(flags, 'session')) +} + export const CHAT_HANDLERS: Record = { 'chat rename': async ({ flags, client, json }) => { const name = getRequiredStringFlag(flags, 'name') @@ -24,34 +77,119 @@ export const CHAT_HANDLERS: Record = { const result = await client .call('agentSession.rename', { sessionId, name }) .catch((error: unknown) => { - throw explainRenameRefusal(error, sessionId) + throw explainChatRefusal(error, sessionId, 'rename') }) if (!result.result.applied) { throw new RuntimeClientError('invalid_argument', 'Not renamed: the name has no visible text.') } printResult(result, json, (value) => `Renamed chat to "${value.name}".`) + }, + 'chat list': async ({ flags, client, cwd, json }) => { + const state = getOptionalStringFlag(flags, 'state') + if (state !== undefined && !AGENT_STATUS_STATES.some((known) => known === state)) { + throw new RuntimeClientError( + 'invalid_argument', + `--state must be one of: ${AGENT_STATUS_STATES.join(', ')}.` + ) + } + const selector = await getOptionalWorktreeSelector(flags, 'worktree', cwd, client) + const shown = selector + ? ( + await client.call<{ worktree: RuntimeWorktreeRecord }>('worktree.show', { + worktree: selector + }) + ).result.worktree + : undefined + const result = await client.call('worktree.ps', {}) + // A local and an SSH copy can share an id; the host tells them apart when both name one. + const worktrees = result.result.worktrees.filter( + (w) => + !shown || + (w.worktreeId === shown.id && + (w.hostId === undefined || shown.hostId === undefined || w.hostId === shown.hostId)) + ) + const chats = listChatSessions(worktrees).filter((chat) => !state || chat.state === state) + printResult({ ...result, result: { chats } }, json, formatChatList) + }, + 'chat read': async ({ flags, client, json }) => { + const session = readSession(flags, client) + const limit = getOptionalPositiveIntegerFlag(flags, 'limit') ?? DEFAULT_READ_LIMIT + if (limit > MAX_READ_LIMIT) { + throw new RuntimeClientError('invalid_argument', `--limit must be at most ${MAX_READ_LIMIT}.`) + } + printResult(await readTranscript(client, session, limit), json, formatChatRead) + }, + 'chat wait': async ({ flags, client, json }) => { + const session = readSession(flags, client) + const timeoutMs = getOptionalPositiveIntegerFlag(flags, 'timeout-ms') + const settled = await waitForChat(client, session, timeoutMs) + printResult(await readSettledTurn(client, session, settled), json, formatSettled) + }, + 'chat send': async ({ flags, client, cwd, json }) => { + const session = readSession(flags, client) + const text = (await readTextOrFileFlag(flags, cwd, 'text', true)) ?? '' + if (text.trim().length === 0) { + throw new RuntimeClientError('invalid_argument', 'The message must not be empty.') + } + const wait = flags.has('wait') + const timeoutMs = getOptionalPositiveIntegerFlag(flags, 'timeout-ms') + const status = await client.getCliStatus() + if (!status.result.runtime.reachable) { + throw new RuntimeClientError( + 'runtime_unavailable', + 'Orca could not reach the execution host, so nothing was sent. Retry once it is reachable.' + ) + } + // A working chat holds a queued message until its turn ends; older hosts get an ordinary send. + const queue = + status.result.runtime.capabilities?.includes( + AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY + ) === true + // The send is fenced to the session's current runtime, so a restarted chat refuses it. + const { page } = (await readHistory(client, session, 1)).result + if (wait) { + requireWorkingFlag(page) + } + const { fence } = page + if (fence === undefined) { + throw new RuntimeClientError( + 'agent_session_not_running', + `Chat ${session} has no running session on this host, so nothing was sent. Open it in Orca and retry.` + ) + } + const mutation = structuredAgentSessionMessageSendMutation({ + sessionId: session, + clientOperationId: createStructuredAgentSessionOperationId(randomUUID), + expectedRuntimeFence: fence, + body: structuredAgentSessionSendBody(text, []), + ...(queue ? { delivery: 'queue-if-active' as const } : {}) + }) + const result = await client.call>( + 'agentSession.send', + mutation + ) + if (!result.result.ok) { + const { code, message } = result.result.refusal + throw explainChatRefusal(new RuntimeClientError(code, message), session, 'send to') + } + const value = result.result.value + const sent = { + session, + delivery: 'queued' in value ? ('queued' as const) : ('submitted' as const), + clientMessageId: value.clientMessageId, + ...('queued' in value ? { queuePosition: value.queued.position } : {}) + } + if (!wait) { + printResult({ ...result, result: sent }, json, (r) => + r.delivery === 'queued' + ? `Queued for ${r.session}; it is sent when the current turn ends.` + : `Sent to ${r.session}.` + ) + return + } + const queuedId = 'queued' in value ? value.queued.messageId : undefined + const settled = await waitForChat(client, session, timeoutMs, queuedId) + const turn = await readSettledTurn(client, session, settled) + printResult({ ...turn, result: { ...sent, ...turn.result } }, json, formatSettled) } } - -// The host answers with bare wire codes; say what they mean for this command. -function explainRenameRefusal(error: unknown, sessionId: string): unknown { - if (!(error instanceof RuntimeClientError)) { - return error - } - if (error.message === 'agent_session_identity_required') { - return new RuntimeClientError( - 'agent_session_identity_required', - `No chat with session id ${sessionId} on this host.` - ) - } - if ( - error.message === 'structured_agent_session_unsupported' || - error.code === 'method_not_found' - ) { - return new RuntimeClientError( - 'incompatible_runtime', - 'This Orca host cannot rename chats from the CLI. Update Orca on that host, or check that it has chats turned on.' - ) - } - return error -} diff --git a/src/cli/handlers/orchestration/worker-agent-views.ts b/src/cli/handlers/orchestration/worker-agent-views.ts index ac76e9c214a..ca993bc66c1 100644 --- a/src/cli/handlers/orchestration/worker-agent-views.ts +++ b/src/cli/handlers/orchestration/worker-agent-views.ts @@ -108,6 +108,7 @@ export type WorkerListResult = { dispatchStatus: string agentTerminalHandle: string | null terminalState: string | null + coordinatedFrom?: string | null resource?: { worktreeId?: string | null; autoReleaseAt?: string | null } | null projection?: WorkerProjection }[] @@ -133,6 +134,7 @@ type WorkerListRow = { terminalState?: string workspace?: string host?: string + coordinatedFrom?: string attention?: string[] autoReleaseAt?: string next?: string @@ -168,6 +170,7 @@ export const WORKER_LIST_VIEW: OrchestrationAgentView = new Set(['agent.launch', 'agent.launchReplay']) +function namesChatCaller(method: string): boolean { + return AGENT_LAUNCH_METHODS.has(method) || method.startsWith('browser.') +} + /** The caller evidence one request carries, read from this process's environment once. */ export class OrchestrationRequestEvidence { private readonly orchestration: RuntimeOrchestrationEnvelope // A chat's session id means nothing on another server, so reads there go like a shell's. private readonly remoteRead: RuntimeOrchestrationEnvelope - private readonly agentLaunchCaller: RuntimeOrchestrationEnvelope['orchestrationCompatibilityEvidence'] + private readonly chatCaller: RuntimeOrchestrationEnvelope['orchestrationCompatibilityEvidence'] constructor(env: NodeJS.ProcessEnv) { this.orchestration = createOrchestrationCompatibilityEnvelope(env) @@ -44,7 +48,7 @@ export class OrchestrationRequestEvidence { ...this.orchestration, orchestrationCompatibilityEvidence: Object.keys(shell).length > 0 ? shell : undefined } - this.agentLaunchCaller = createAgentLaunchCallerEvidence(env) + this.chatCaller = createChatCallerEvidence(env) } envelopeFor( @@ -58,8 +62,8 @@ export class OrchestrationRequestEvidence { compatibilityInvocationId: request.requestId ?? base.compatibilityInvocationId } } - return AGENT_LAUNCH_METHODS.has(method) && !request.remote && this.agentLaunchCaller - ? { orchestrationCompatibilityEvidence: this.agentLaunchCaller } + return namesChatCaller(method) && !request.remote && this.chatCaller + ? { orchestrationCompatibilityEvidence: this.chatCaller } : {} } } diff --git a/src/cli/runtime/orchestration-request-evidence.test.ts b/src/cli/runtime/orchestration-request-evidence.test.ts index aceef390bc2..e8234f2223a 100644 --- a/src/cli/runtime/orchestration-request-evidence.test.ts +++ b/src/cli/runtime/orchestration-request-evidence.test.ts @@ -26,3 +26,18 @@ describe('caller evidence on requests to another server', () => { ).toEqual({ agentSessionId: '11111111-1111-4111-8111-111111111111' }) }) }) + +describe('caller evidence on browser commands', () => { + it('names the chat on this host, so its run can show the page it drove', () => { + const evidence = new OrchestrationRequestEvidence(CHAT) + const request = { mutation: false, requestId: undefined } + expect( + evidence.envelopeFor('browser.click', { ...request, remote: false }) + .orchestrationCompatibilityEvidence + ).toEqual({ agentSessionId: '11111111-1111-4111-8111-111111111111' }) + expect( + evidence.envelopeFor('browser.click', { ...request, remote: true }) + .orchestrationCompatibilityEvidence + ).toBeUndefined() + }) +}) diff --git a/src/cli/specs/browser-basic.ts b/src/cli/specs/browser-basic.ts index 2d9ea0f589e..b25628d9e4a 100644 --- a/src/cli/specs/browser-basic.ts +++ b/src/cli/specs/browser-basic.ts @@ -206,6 +206,12 @@ export const BROWSER_BASIC_COMMAND_SPECS: CommandSpec[] = withBrowserPageTarget( usage: 'orca tab show --page [--worktree ] [--json]', allowedFlags: [...GLOBAL_FLAGS, 'page', 'worktree'] }, + { + path: ['tab', 'annotations'], + summary: "Show the notes the user left on a browser tab and hasn't sent yet", + usage: 'orca tab annotations [--page ] [--worktree ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'page', 'worktree'] + }, { path: ['tab', 'current'], summary: 'Show the current browser tab', diff --git a/src/cli/specs/chat.ts b/src/cli/specs/chat.ts index 28fb41556dd..ae73e34d6ed 100644 --- a/src/cli/specs/chat.ts +++ b/src/cli/specs/chat.ts @@ -15,5 +15,57 @@ export const CHAT_COMMAND_SPECS: CommandSpec[] = [ 'orca chat rename --name "Migrate auth to OAuth"', 'orca chat rename --session --name "Release notes" --json' ] + }, + { + path: ['chat', 'list'], + summary: 'List agent chats with their workspace, state and last reply', + usage: 'orca chat list [--worktree ] [--state ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'worktree', 'state'], + notes: [ + 'Lists the top-level chats Orca shows as agent tabs. Terminal agents are read with `orca terminal`.', + '--state keeps chats in one state: working, blocked, waiting or done.' + ], + examples: ['orca chat list --json', 'orca chat list --state working'] + }, + { + path: ['chat', 'read'], + summary: 'Read the latest messages of an agent chat', + usage: 'orca chat read --session [--limit ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'session', 'limit'], + notes: [ + '--session takes the session id or handle from `orca chat list` or `orca agent launch`.', + '--limit is the number of entries shown (messages, tool calls, approvals and questions); the default is 20 and the maximum 100.', + 'Approvals and questions waiting for an answer are marked "waiting for you".' + ], + examples: ['orca chat read --session codex_1234 --limit 10'] + }, + { + path: ['chat', 'send'], + summary: 'Send a message to an agent chat', + usage: + 'orca chat send --session (--text | --text-file ) [--wait] [--timeout-ms ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'session', 'text', 'text-file', 'wait', 'timeout-ms'], + notes: [ + 'Sends the text as your message, as if typed in the chat. --text-file - reads it from stdin.', + 'While the agent is working, hosts with a message queue hold the message until the turn ends; the result says "queued".', + '--wait returns once the chat finishes or waits for your answer, with what it did since your message. It exits 1 when the wait times out or the message is held in a stopped queue.', + 'A chat that restarted since it was read refuses the send; read it again and resend.' + ], + examples: [ + 'orca chat send --session codex_1234 --text "Run the tests, then summarize failures"', + 'orca chat send --session codex_1234 --text "Run the tests" --wait --timeout-ms 600000 --json', + 'cat notes.md | orca chat send --session codex_1234 --text-file -' + ] + }, + { + path: ['chat', 'wait'], + summary: 'Wait until an agent chat finishes or needs your answer', + usage: 'orca chat wait --session [--timeout-ms ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'session', 'timeout-ms'], + notes: [ + 'Settles on the chat\'s own turn, in `chat list` words: "done", or "blocked" on an approval or question. Background agents it started can still show as working or waiting in `chat list`. "held" and "timeout" exit 1.', + 'Prints what the chat did since the last user message. A wait that times out exits 1.' + ], + examples: ['orca chat wait --session codex_1234 --timeout-ms 600000 --json'] } ] diff --git a/src/main/acp/discovery/acp-model-catalog-probe.test.ts b/src/main/acp/discovery/acp-model-catalog-probe.test.ts new file mode 100644 index 00000000000..bbb5943d4b2 --- /dev/null +++ b/src/main/acp/discovery/acp-model-catalog-probe.test.ts @@ -0,0 +1,89 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { acpLaunchSpecFor } from '../launch/acp-launch-registry' +import type { AcpLaunchSpec } from '../launch/acp-launch-contract' +import { createAcpModelCatalogProbe } from './acp-model-catalog-probe' +import { AcpSessionRuntime } from '../protocol/acp-session-runtime' +import { AcpScriptedAgent } from '../process/testing/acp-scripted-agent.test-support' +import { openCodeAcpAccountBinding } from '../../opencode/opencode-structured-account-home' + +// Bypass the app's managed-account service for this fixture. +const OPENCODE: AcpLaunchSpec = { + ...acpLaunchSpecFor('opencode')!, + account: openCodeAcpAccountBinding(() => ({ + list: () => ({ activeAccountId: null, accounts: [] }), + restoreOriginalEnvironment: () => {}, + environmentForAccount: () => ({}) + })) +} + +const agents: AcpScriptedAgent[] = [] +afterEach(() => { + for (const agent of agents.splice(0)) { + agent.close() + } +}) + +describe('ACP model catalog probes', () => { + it('lists the catalog after OpenCode answers session/new with -32603 while starting', async () => { + const agent = new AcpScriptedAgent() + agents.push(agent) + agent.on('initialize', (frame) => + agent.reply(frame, { + protocolVersion: 1, + agentCapabilities: { sessionCapabilities: { delete: {} } } + }) + ) + let sessionNews = 0 + agent.on('session/new', (frame) => { + sessionNews += 1 + if (sessionNews === 1) { + agent.fail(frame, -32603, 'Internal error: Internal service failure', { + errorName: 'InvalidRequestError' + }) + return + } + agent.reply(frame, { + sessionId: 'probe-session', + configOptions: [ + { + id: 'model', + name: 'Model', + category: 'model', + type: 'select', + currentValue: 'opencode/exo-free', + options: [ + { value: 'opencode/big-pickle', name: 'Big Pickle' }, + { value: 'opencode/exo-free', name: 'Exo Free' } + ] + } + ] + }) + }) + agent.on('session/delete', (frame) => agent.reply(frame, {})) + agent.on('session/set_config_option', (frame) => agent.fail(frame, -32602, 'Model unavailable')) + + const success = await createAcpModelCatalogProbe(OPENCODE, { + resolveEnvironment: async () => ({ PATH: '/usr/bin', HOME: '/home/user' }), + resolveCommand: () => '/opt/opencode/bin/opencode', + probeVersion: async () => ({ version: '2.0.29' }), + homePath: '/home/user', + dataDirectory: '/orca-data', + connectSession: () => { + const runtime = new AcpSessionRuntime(agent.stdout, agent.stdin) + return { + initialize: () => runtime.initialize(), + start: (options) => runtime.start(options), + setConfigOption: (id, value) => runtime.setConfigOption(id, value), + deleteSession: (sessionId) => runtime.deleteSession(sessionId), + close: async () => runtime.close() + } + } + })({ kind: 'opencode', locator: { kind: 'unmanaged' } }, { workspacePath: '/work/project' }) + + expect(sessionNews).toBe(2) + expect(success.models.map((model) => model.id)).toEqual([ + 'opencode/big-pickle', + 'opencode/exo-free' + ]) + }) +}) diff --git a/src/main/acp/discovery/acp-model-catalog-probe.ts b/src/main/acp/discovery/acp-model-catalog-probe.ts index 7df8a4a31f9..ecf6ad7ac0b 100644 --- a/src/main/acp/discovery/acp-model-catalog-probe.ts +++ b/src/main/acp/discovery/acp-model-catalog-probe.ts @@ -4,6 +4,7 @@ import { type StructuredAgentResolutionOperation } from '../../native-chat/structured-agent-command-resolution' import { homedir } from 'node:os' +import { setTimeout as delay } from 'node:timers/promises' import { join } from 'node:path' import type { AgentCliVersionReader } from '../../agent-launch/preflight/agent-cli-version-probe' import type { AgentModelCatalogProbe } from '../../native-chat/agent-model-catalog/agent-model-catalog-store' @@ -190,6 +191,26 @@ export function createAcpModelCatalogProbe( const folderlessListing = (spec: AcpLaunchSpec) => new AgentModelCatalogListingStoppedError(`${spec.agent} lists in a chat's folder`) +// OpenCode can answer -32603 while its providers are still opening; a later attempt lists them. +async function startListingSession( + connection: AcpModelCatalogSessionConnection, + workspace: string, + operation?: StructuredAgentResolutionOperation +): Promise { + for (const backoffMs of [250, 500]) { + try { + return await connection.start({ cwd: workspace, mcpServers: [] }) + } catch (error) { + if (!(error instanceof AcpAgentError && error.code === -32603)) { + throw error + } + } + await delay(backoffMs, undefined, { signal: operation?.signal }) + assertStructuredAgentResolutionCurrent(operation) + } + return connection.start({ cwd: workspace, mcpServers: [] }) +} + async function readSessionModels( spec: AcpLaunchSpec, listing: AcpSessionModelDiscovery, @@ -206,7 +227,7 @@ async function readSessionModels( if (!deletes && !listing.sessionFolderArgs) { throw new Error(`${spec.agent} cannot delete a session, so it lists its models only in chats`) } - const started = await connection.start({ cwd: workspace, mcpServers: [] }) + const started = await startListingSession(connection, workspace, operation) let stopped = false const cleanup = async (): Promise => { stopped = true diff --git a/src/main/agent-hooks/installation/commands/managed-hook-command-matching.ts b/src/main/agent-hooks/installation/commands/managed-hook-command-matching.ts index 82b599b4a5e..80232cc79d2 100644 --- a/src/main/agent-hooks/installation/commands/managed-hook-command-matching.ts +++ b/src/main/agent-hooks/installation/commands/managed-hook-command-matching.ts @@ -6,9 +6,7 @@ import { import type { HookCommandConfig, HookDefinition } from '../configuration/hook-config-schema' // Match script names so reinstalls sweep entries from old and parallel installations. -export function createManagedCommandMatcher( - scriptFileName: string -): (command: string | undefined) => boolean { +export function createManagedCommandMatcher(scriptFileName: string): (command: unknown) => boolean { const scriptStem = scriptFileName.replace(/\.(?:cmd|ps1|sh)$/, '') // Sweep every platform suffix after a platform switch. const needles = [ @@ -19,8 +17,9 @@ export function createManagedCommandMatcher( ] // The native executable selects its provider through argv[1]. const nativeHook = `agent-hooks/${WINDOWS_NATIVE_HOOK_EXECUTABLE_NAME} ${getWindowsNativeHookAgent(scriptFileName)} ` + // hooks.json is user-editable, so a command may not be a string. return (command) => { - if (!command) { + if (typeof command !== 'string' || !command) { return false } const decodedCommand = decodePowerShellEncodedCommand(command) diff --git a/src/main/browser/agent-browser/command-queue/agent-browser-bridge-queue.ts b/src/main/browser/agent-browser/command-queue/agent-browser-bridge-queue.ts index eafd92c5188..5b4969e02da 100644 --- a/src/main/browser/agent-browser/command-queue/agent-browser-bridge-queue.ts +++ b/src/main/browser/agent-browser/command-queue/agent-browser-bridge-queue.ts @@ -20,7 +20,7 @@ import { captureRemoteCliBrowserScope, runOutsideRemoteCliBrowserScope } from '../../../runtime/desktop-browser-bridge/remote-cli-browser-scope' -import { getActiveRpcCaller } from '../../../runtime/rpc/rpc-active-caller' +import { captureActiveRpcCall, getActiveRpcCaller } from '../../../runtime/rpc/rpc-active-caller' export abstract class AgentBrowserBridgeQueue extends AgentBrowserBridgeActionEffects { // Serialize tab switches behind commands targeting the current tab. @@ -97,8 +97,10 @@ export abstract class AgentBrowserBridgeQueue extends AgentBrowserBridgeActionEf assertNoJavaScriptDialog(webContentsId, pageId, assertNotRevoked) const sessionName = `${ORCA_TAB_SESSION_PREFIX}${pageId}` const agentCommand = this.browserManager.beginAgentCommand(pageId) - // Queued commands run under the caller ahead of them, so read this one's caller now. + // Queued commands run under the caller ahead of them, so read this one's caller now + // and re-enter its call, or what it marks would count as that other chat's. const caller = getActiveRpcCaller() + const inThisCall = captureActiveRpcCall() // Decided at enqueue: a queued command runs under the caller of the command ahead of it. const reportEffects = options.reportEffects === true && agentCommand.agent const expectedUrl = getRequestedPageUrl() @@ -167,10 +169,12 @@ export abstract class AgentBrowserBridgeQueue extends AgentBrowserBridgeActionEf }, options ) - return origin.run(() => { - started = true - return this.browserManager.runPageCommand(pageId, caller, () => agentCommand.run(run)) - }) + return inThisCall(() => + origin.run(() => { + started = true + return this.browserManager.runPageCommand(pageId, caller, () => agentCommand.run(run)) + }) + ) }, resolve: resolve as (value: unknown) => void, reject diff --git a/src/main/browser/agent-browser/session-routing/agent-browser-bridge-tab-routing.test.ts b/src/main/browser/agent-browser/session-routing/agent-browser-bridge-tab-routing.test.ts index ce28eaa77df..7f8838bd535 100644 --- a/src/main/browser/agent-browser/session-routing/agent-browser-bridge-tab-routing.test.ts +++ b/src/main/browser/agent-browser/session-routing/agent-browser-bridge-tab-routing.test.ts @@ -59,6 +59,10 @@ vi.mock('../../cdp/commands/cdp-bridge', async () => { }) import { AgentBrowserBridge } from '../agent-browser-bridge' +import { + getActiveRpcAgentSessionId, + runWithActiveRpcCaller +} from '../../../runtime/rpc/rpc-active-caller' import { answerAgentBrowserCommands, mockBrowserManager, @@ -125,4 +129,51 @@ describe('AgentBrowserBridge', () => { await b.click('@e2', 'wt-1') expect(clickSessions).toEqual(['orca-tab-tab-a', 'orca-tab-tab-b']) }) + + it("marks a tab switch queued behind another chat's command as the switching chat's", async () => { + const chatA = '11111111-1111-4111-8111-111111111111' + const chatB = '22222222-2222-4222-8222-222222222222' + const tabs = new Map([ + ['tab-a', 1], + ['tab-b', 2] + ]) + const worktrees = new Map([ + ['tab-a', 'wt-1'], + ['tab-b', 'wt-1'] + ]) + const wc1 = mockWebContents(1) + const wc2 = mockWebContents(2) + webContentsFromIdMock.mockImplementation((id: number) => (id === 1 ? wc1 : wc2)) + const marks: [string, string | undefined][] = [] + const b = new AgentBrowserBridge( + mockBrowserManager(tabs, worktrees, { + beginAgentCommand: (pageId: string) => { + marks.push([pageId, getActiveRpcAgentSessionId()]) + return { agent: true, run: (execute) => execute(), end: () => {} } + } + }) + ) + b.setActiveTab(1, 'wt-1') + const held: { releaseA?: () => void } = {} + answerAgentBrowserCommands(execFileMock, stdinWrites, (_command, cb) => { + const answer = (): void => + cb(null, JSON.stringify({ success: true, data: { snapshot: '' } }), '') + if (held.releaseA) { + answer() + } else { + held.releaseA = answer + } + }) + const inChat = (chat: string, run: () => T): T => + runWithActiveRpcCaller({ kind: 'local-cli' }, run, chat) + + const snapshot = inChat(chatA, () => b.snapshot('wt-1')) + await vi.waitFor(() => expect(execFileMock).toHaveBeenCalled()) + const tabSwitch = inChat(chatB, () => b.tabSwitch(undefined, 'wt-1', 'tab-b')) + held.releaseA?.() + await Promise.all([snapshot, tabSwitch]) + + expect(marks).toContainEqual(['tab-b', chatB]) + expect(marks).not.toContainEqual(['tab-b', chatA]) + }) }) diff --git a/src/main/browser/cdp/commands/cdp-screenshot.ts b/src/main/browser/cdp/commands/cdp-screenshot.ts index f43f5c1e194..76cc4726365 100644 --- a/src/main/browser/cdp/commands/cdp-screenshot.ts +++ b/src/main/browser/cdp/commands/cdp-screenshot.ts @@ -1,4 +1,8 @@ -import type { CapturePaintHold } from '../debugger/guest-paint-hold' +import { + holdPaintUntilCdpCaptureSettles, + holdPaintUntilSettled, + type CapturePaintHold +} from '../debugger/guest-paint-hold' import type { WebContents } from 'electron' import { sendGuestCdpCommand } from '../debugger/guest-cdp-command' import { @@ -137,7 +141,8 @@ export function withTimeout( // Undrawn pages can leave captures pending; cheap probes trigger a frame for the original request. function captureUntilDrawn( webContents: WebContents, - params: Record + params: Record, + holdPaint: CapturePaintHold ): Promise<{ data: string } | null> { return new Promise((resolve, reject) => { let settled = false @@ -173,12 +178,12 @@ function captureUntilDrawn( } catch { // Guest teardown can reject repaint requests; still try CDP. } - return sendGuestCdpCommand(webContents, 'Page.captureScreenshot', requestParams).then( - (result) => { - const data = isRecord(result) ? result.data : undefined - return typeof data === 'string' ? { data } : undefined - } - ) + return holdPaintUntilCdpCaptureSettles(webContents, holdPaint, () => + sendGuestCdpCommand(webContents, 'Page.captureScreenshot', requestParams) + ).then((result) => { + const data = isRecord(result) ? result.data : undefined + return typeof data === 'string' ? { data } : undefined + }) } const deadline = setTimeout(() => finish(() => resolve(null)), SCREENSHOT_TIMEOUT_MS) let probes: NodeJS.Timeout[] = [] @@ -223,11 +228,15 @@ export async function captureFullPageScreenshot( if (!clip) { throw new Error('Unable to determine full-page screenshot bounds') } - const frame = await captureUntilDrawn(webContents, { - format, - captureBeyondViewport: true, - clip - }) + const frame = await captureUntilDrawn( + webContents, + { + format, + captureBeyondViewport: true, + clip + }, + holdPaint + ) if (!frame) { throw new Error(SCREENSHOT_TIMEOUT_MESSAGE) } @@ -269,13 +278,13 @@ export async function captureScreenshot( const release = holdPaint() try { - const frame = await captureUntilDrawn(webContents, screenshotParams) + const frame = await captureUntilDrawn(webContents, screenshotParams, holdPaint) if (frame) { return frame } const fallback = await readRemoteCliAdmittedPage(webContents.id, () => withTimeout( - Promise.resolve().then(() => webContents.capturePage()), + holdPaintUntilSettled(holdPaint, () => webContents.capturePage()), FALLBACK_CAPTURE_TIMEOUT_MS, SCREENSHOT_TIMEOUT_MESSAGE ) diff --git a/src/main/browser/cdp/debugger/guest-paint-hold.ts b/src/main/browser/cdp/debugger/guest-paint-hold.ts index 885a3e98a84..c235cf72541 100644 --- a/src/main/browser/cdp/debugger/guest-paint-hold.ts +++ b/src/main/browser/cdp/debugger/guest-paint-hold.ts @@ -1,2 +1,41 @@ +import type { WebContents } from 'electron' +import { acquireElectronDebugger } from './electron-debugger-lease' + /** Draws a hidden guest while a capture or agent input needs its frames; returns its release. */ export type CapturePaintHold = () => () => void + +function retainUntilSettled(acquire: () => () => void, run: () => Promise): Promise { + let release: () => void + try { + release = acquire() + } catch (error) { + return Promise.reject(error) + } + const pending = new Promise((resolve) => resolve(run())) + void pending.then(release, release) + return pending +} + +/** + * Holds paint until Chromium answers the capture, not just while the caller waits. A capture stays + * pending until the guest draws, and while pending it can hold macOS display sleep off ("Capturing"); + * timeouts do not cancel it (#24946). + */ +export function holdPaintUntilSettled( + holdPaint: CapturePaintHold, + capture: () => Promise +): Promise { + return retainUntilSettled(holdPaint, capture) +} + +/** Also keeps the debugger attached: a detach rejects the command while Chromium keeps the capture. */ +export function holdPaintUntilCdpCaptureSettles( + webContents: WebContents, + holdPaint: CapturePaintHold, + capture: () => Promise +): Promise { + return retainUntilSettled( + () => acquireElectronDebugger(webContents).release, + () => retainUntilSettled(holdPaint, capture) + ) +} diff --git a/src/main/browser/cdp/screencast/browser-screencast-first-frame-timeout.test.ts b/src/main/browser/cdp/screencast/browser-screencast-first-frame-timeout.test.ts index 797f2ff07a5..8129fb06766 100644 --- a/src/main/browser/cdp/screencast/browser-screencast-first-frame-timeout.test.ts +++ b/src/main/browser/cdp/screencast/browser-screencast-first-frame-timeout.test.ts @@ -24,6 +24,7 @@ function startOptions(viewport: boolean) { maxHeight: 1200, everyNthFrame: 2, minFrameIntervalMs: 0, + holdPaint: () => () => {}, ...(viewport ? { viewportWidth: 390, viewportHeight: 844 } : {}), onFrame: vi.fn(() => true), onError: vi.fn() @@ -59,6 +60,49 @@ describe('browser screencast first-frame deadline', () => { await session.done }) + it('keeps the page drawable until Chromium answers the captures the stream gave up on', async () => { + let settleCapture!: (image: unknown) => void + const webContents = Object.assign(createMockScreencastWebContents(), { + capturePage: vi.fn( + () => + new Promise((resolve) => { + settleCapture = resolve + }) + ) + }) + let settleScreenshot!: (result: unknown) => void + let rejectScreenshot!: (error: Error) => void + webContents.debugger.sendCommand.mockImplementation(async (method: string) => + method === 'Page.captureScreenshot' + ? new Promise((resolve, reject) => { + settleScreenshot = resolve + rejectScreenshot = reject + }) + : {} + ) + // Electron rejects pending commands on detach, but Chromium keeps the capture. + webContents.debugger.detach.mockImplementation(() => + rejectScreenshot(new Error('target closed while handling command')) + ) + const releasePaint = vi.fn() + const options = { ...startOptions(true), holdPaint: vi.fn(() => releasePaint) } + const session = await start(webContents, options) + + // capturePage's 10 s bound, then the CDP fallback's 8 s. + await vi.advanceTimersByTimeAsync(18_000) + session.stop() + await session.done + expect(options.holdPaint).toHaveBeenCalledTimes(2) + expect(webContents.debugger.detach).not.toHaveBeenCalled() + expect(releasePaint).not.toHaveBeenCalled() + + settleCapture({ getSize: () => ({ width: 0, height: 0 }) }) + settleScreenshot({}) + await vi.advanceTimersByTimeAsync(0) + expect(releasePaint).toHaveBeenCalledTimes(2) + expect(webContents.debugger.detach).toHaveBeenCalledOnce() + }) + it('drops a capture that settles after the limit', async () => { let settleCapture!: (image: unknown) => void const webContents = Object.assign(createMockScreencastWebContents(), { diff --git a/src/main/browser/cdp/screencast/browser-screencast-guest-view-limit.test.ts b/src/main/browser/cdp/screencast/browser-screencast-guest-view-limit.test.ts index 5968bf42069..a07487bfd5b 100644 --- a/src/main/browser/cdp/screencast/browser-screencast-guest-view-limit.test.ts +++ b/src/main/browser/cdp/screencast/browser-screencast-guest-view-limit.test.ts @@ -70,6 +70,7 @@ async function startOversizedStream(guest: ReturnType, onFra deviceScaleFactor: 2, everyNthFrame: 1, minFrameIntervalMs: 0, + holdPaint: () => () => {}, onFrame }) } diff --git a/src/main/browser/cdp/screencast/browser-screencast-lifecycle.test.ts b/src/main/browser/cdp/screencast/browser-screencast-lifecycle.test.ts index 09889e723c7..4443f28f7e3 100644 --- a/src/main/browser/cdp/screencast/browser-screencast-lifecycle.test.ts +++ b/src/main/browser/cdp/screencast/browser-screencast-lifecycle.test.ts @@ -35,6 +35,7 @@ describe('browser screencast lifecycle', () => { maxHeight: 2160, everyNthFrame: 2, minFrameIntervalMs: 0, + holdPaint: () => () => {}, onFrame }) @@ -80,6 +81,7 @@ describe('browser screencast lifecycle', () => { maxHeight: 1200, everyNthFrame: 2, minFrameIntervalMs: 0, + holdPaint: () => () => {}, onFrame: vi.fn() }, isClosed: () => false, diff --git a/src/main/browser/cdp/screencast/browser-screencast-live-frame-allocation.test.ts b/src/main/browser/cdp/screencast/browser-screencast-live-frame-allocation.test.ts index 0d61e942a80..86185d11b0b 100644 --- a/src/main/browser/cdp/screencast/browser-screencast-live-frame-allocation.test.ts +++ b/src/main/browser/cdp/screencast/browser-screencast-live-frame-allocation.test.ts @@ -40,6 +40,7 @@ function createLiveFrameRoute( maxHeight: 1200, everyNthFrame: 2, minFrameIntervalMs: 0, + holdPaint: () => () => {}, onFrame } const isClosed = () => false 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 733a4cb542a..b9b3c1f037d 100644 --- a/src/main/browser/cdp/screencast/browser-screencast-snapshot-capture.ts +++ b/src/main/browser/cdp/screencast/browser-screencast-snapshot-capture.ts @@ -1,7 +1,11 @@ import { Buffer } from 'node:buffer' import type { Debugger, WebContents } from 'electron' import { readBrowserScreencastImageSize } from './browser-screencast-image-size' -import { sendDebuggerCommand } from './browser-screencast-debugger-command' +import { runDebuggerCommandWithTimeout } from './browser-screencast-debugger-command' +import { + holdPaintUntilCdpCaptureSettles, + holdPaintUntilSettled +} from '../debugger/guest-paint-hold' import type { BrowserScreencastOptions, PendingScreencastFrame @@ -35,6 +39,7 @@ export function createBrowserScreencastSnapshotCapture( ): BrowserScreencastSnapshotCapture { const { webContents, dbg, options, isClosed, isStopping, getSeq, queueFrame } = deps const { applyDeviceMetricsOverride } = deps + const { holdPaint } = options let snapshotGeneration = 0 let navigationCaptureTimer: ReturnType | null = null @@ -81,7 +86,9 @@ export function createBrowserScreencastSnapshotCapture( try { // Prefer capturePage to avoid CDP tiling; stopped compositing can leave it pending. const nativeImage = await withTimeout( - webContents.capturePage({ x: 0, y: 0, width: viewportWidth, height: viewportHeight }), + holdPaintUntilSettled(holdPaint, () => + webContents.capturePage({ x: 0, y: 0, width: viewportWidth, height: viewportHeight }) + ), SNAPSHOT_CAPTURE_TIMEOUT_MS, null ) @@ -101,7 +108,7 @@ export function createBrowserScreencastSnapshotCapture( } } if (!image) { - const result = await sendDebuggerCommand(dbg, 'Page.captureScreenshot', { + const screenshotParams = { format: options.format, ...(options.format === 'jpeg' ? { quality: options.quality } : {}), ...(viewportWidth && viewportHeight @@ -117,7 +124,12 @@ export function createBrowserScreencastSnapshotCapture( } : {}), captureBeyondViewport: false - }) + } + const result = await runDebuggerCommandWithTimeout('Page.captureScreenshot', () => + holdPaintUntilCdpCaptureSettles(webContents, holdPaint, () => + dbg.sendCommand('Page.captureScreenshot', screenshotParams) + ) + ) if (isSnapshotStale(initialOnly, generation)) { return } diff --git a/src/main/browser/cdp/screencast/browser-screencast-stream-types.ts b/src/main/browser/cdp/screencast/browser-screencast-stream-types.ts index 0676e970411..666bba266b2 100644 --- a/src/main/browser/cdp/screencast/browser-screencast-stream-types.ts +++ b/src/main/browser/cdp/screencast/browser-screencast-stream-types.ts @@ -2,6 +2,7 @@ import type { BrowserScreencastFormat, BrowserScreencastFrameMetadata } from '../../../../shared/browser/screencast/browser-screencast-protocol' +import type { CapturePaintHold } from '../debugger/guest-paint-hold' export type BrowserScreencastOptions = { format: BrowserScreencastFormat @@ -17,6 +18,7 @@ export type BrowserScreencastOptions = { onFrame: (bytes: Uint8Array) => boolean | void onEvent?: (event: BrowserScreencastEvent) => void onError?: (message: string) => void + holdPaint: CapturePaintHold } export type BrowserScreencastViewport = Pick< 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 6870a27f172..456ff1f213c 100644 --- a/src/main/browser/cdp/screencast/browser-screencast-stream.test.ts +++ b/src/main/browser/cdp/screencast/browser-screencast-stream.test.ts @@ -27,6 +27,7 @@ describe('startBrowserScreencast', () => { maxHeight: 1200, everyNthFrame: 1, minFrameIntervalMs: 0, + holdPaint: () => () => {}, onFrame }) @@ -84,6 +85,7 @@ describe('startBrowserScreencast', () => { maxHeight: 1200, everyNthFrame: 1, minFrameIntervalMs: 100, + holdPaint: () => () => {}, onFrame }) @@ -136,6 +138,7 @@ describe('startBrowserScreencast', () => { maxHeight: 1200, everyNthFrame: 2, minFrameIntervalMs: 0, + holdPaint: () => () => {}, onFrame: vi.fn(), onEvent }) diff --git a/src/main/browser/desktop-browser-bridge/desktop-browser-bridge-executor.ts b/src/main/browser/desktop-browser-bridge/desktop-browser-bridge-executor.ts index abff471a47b..888cdbb736a 100644 --- a/src/main/browser/desktop-browser-bridge/desktop-browser-bridge-executor.ts +++ b/src/main/browser/desktop-browser-bridge/desktop-browser-bridge-executor.ts @@ -256,22 +256,3 @@ function urlOrigin(value: unknown): string | null { return null } } - -// Routed tabs can still display local files; those remain off-limits to hosts. -// Allow chrome-error: so hosts can navigate away from failed loads. -const HOST_REACHABLE_DOCUMENT_PROTOCOLS = new Set([ - 'http:', - 'https:', - 'about:', - 'blob:', - 'data:', - 'chrome-error:' -]) - -export function isHostReachableDocument(url: string): boolean { - try { - return HOST_REACHABLE_DOCUMENT_PROTOCOLS.has(new URL(url).protocol) - } catch { - return url === '' - } -} 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 8a2148e204f..d11c363277f 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 @@ -90,6 +90,18 @@ describe('BrowserAgentActivity', () => { expect(sent).toEqual([]) }) + it("names the chat whose agent's CLI sent the command", () => { + const { activity, sent } = setup() + const chat = '11111111-1111-4111-8111-111111111111' + runWithActiveRpcCaller({ kind: 'local-cli' }, () => activity.beginCommand(PAGE), chat).end() + expect(sent.at(-1)?.data).toEqual({ + browserPageId: PAGE, + worktreeId: 'wt-1', + active: true, + agentSessionId: chat + }) + }) + it('clears the mark once the agent stays idle, and at once when the page closes', () => { const { activity, sent, agentCommand } = setup() agentCommand().end() 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 b698b215aab..33bd6cf2ef6 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 @@ -9,7 +9,10 @@ import { type BrowserAgentActivityEvent, type BrowserAgentCursorEvent } from '../../../../shared/browser-agent-activity-contract' -import { getActiveRpcCaller } from '../../../runtime/rpc/rpc-active-caller' +import { + getActiveRpcAgentSessionId, + getActiveRpcCaller +} from '../../../runtime/rpc/rpc-active-caller' import { remoteCliBrowserScopeController, type RemoteCliBrowserController @@ -35,6 +38,8 @@ type PageActivity = { idleTimer: ReturnType | null /** The SSH host whose command marked the page last, if it came through the desktop bridge. */ controller: RemoteCliBrowserController | null + /** The chat whose agent marked the page last, when its CLI named one. */ + agentSessionId: string | undefined } /** One page-targeted command, held from when it is queued until it settles. */ @@ -80,12 +85,19 @@ export class BrowserAgentActivity { } let page = this.pages.get(browserPageId) if (!page) { - page = { commands: 0, executing: false, idleTimer: null, controller: null } + page = { + commands: 0, + executing: false, + idleTimer: null, + controller: null, + agentSessionId: undefined + } this.pages.set(browserPageId, page) } page.controller = remoteCliBrowserScopeController() ?? null + page.agentSessionId = getActiveRpcAgentSessionId() // Every command republishes, so a reloaded or newly attached window catches up. - this.publish(browserPageId, true, page.controller) + this.publish(browserPageId, true, page) if (page.idleTimer) { clearTimeout(page.idleTimer) page.idleTimer = null @@ -122,20 +134,22 @@ export class BrowserAgentActivity { /** The agent continues on another page (a closed popup's opener), so its claim moves there. */ handOver(fromPageId: string, toPageId: string): void { const existing = this.pages.get(toPageId) + const from = this.pages.get(fromPageId) // A running command restarts the idle window itself when it settles. - if (!this.pages.has(fromPageId) || (existing && existing.commands > 0)) { + if (!from || (existing && existing.commands > 0)) { return } const page = existing ?? { commands: 0, executing: false, idleTimer: null, - controller: this.pages.get(fromPageId)?.controller ?? null + controller: from.controller, + agentSessionId: from.agentSessionId } this.restartIdleWindow(toPageId, page) if (!existing) { this.pages.set(toPageId, page) - this.publish(toPageId, true, page.controller) + this.publish(toPageId, true, page) } } @@ -251,7 +265,7 @@ export class BrowserAgentActivity { private publish( browserPageId: string, active: boolean, - controller: RemoteCliBrowserController | null = null + { controller, agentSessionId }: Partial = {} ): void { const renderer = this.deps.rendererForPage(browserPageId) if (renderer && !renderer.isDestroyed()) { @@ -259,7 +273,8 @@ export class BrowserAgentActivity { browserPageId, worktreeId: this.deps.worktreeForPage(browserPageId), active, - ...(controller ? { controllerHostLabel: controller.hostLabel } : {}) + ...(controller ? { controllerHostLabel: controller.hostLabel } : {}), + ...(agentSessionId ? { agentSessionId } : {}) } renderer.send(BROWSER_AGENT_ACTIVITY_CHANNEL, event) } diff --git a/src/main/claude-accounts/claude-profile-provisioning.test.ts b/src/main/claude-accounts/claude-profile-provisioning.test.ts index 58b70c7aa23..98684a185df 100644 --- a/src/main/claude-accounts/claude-profile-provisioning.test.ts +++ b/src/main/claude-accounts/claude-profile-provisioning.test.ts @@ -131,18 +131,37 @@ describe('Claude profile refresh from the default home', () => { expect((await provision(f)).surfaces['settings.json']).toBe('user-owned') expect(f.read(elsewhere)).toEqual({ mine: true }) }) - it('copies state except the login, caches and install ids, and never copies credentials', async () => { + it('shares configuration while keeping profile runtime state and API authorizations private', async () => { const f = fixture() fs.writeFileSync(join(f.source, '.credentials.json'), 'SOURCE_CREDENTIAL_BYTES') const shared = { mcpServers: { local: { command: 'example' } }, theme: 'dark', hasCompletedOnboarding: true, - autoModeAccepted: true, + bypassPermissionsModeAccepted: true, + favoritePlugins: ['favorite@example'], + preferTmuxOverIterm2: true, + codeReviewLastEffort: 'high', + codeReviewLastMaxFindings: 3, + installMethod: 'global', + autoUpdates: false, + autoUpdatesProtectedForNative: false, + customApiKeyResponses: { rejected: ['PERSONAL_REJECTED_SUFFIX'] }, projects: { '/work': { hasTrustDialogAccepted: true } } } - f.json(join(f.userHome, '.claude.json'), { + const personal = { ...shared, + customApiKeyResponses: { + approved: ['PERSONAL_APPROVED_SUFFIX'], + rejected: ['PERSONAL_REJECTED_SUFFIX'] + }, + groveChoiceSeenAt: { personal: 1 }, + numStartups: 2, + tipsHistory: { tip: 1 }, + seenNotifications: { notice: 1 }, + penguinModeOrgEnabled: false, + futureRuntimeState: { personal: true }, + autoModeAccepted: true, oauthAccount: { emailAddress: 'source@example.com' }, primaryApiKey: 'sk-source', userID: 'source-id', @@ -150,7 +169,6 @@ describe('Claude profile refresh from the default home', () => { firstStartTime: 'source-start', firstStartVersion: '1.0.0', groveConfigCache: { a: 1 }, - groveChoiceSeenAt: { 'account-a': 99, 'account-b': 10 }, cachedArtifactRoster: [], clientDataCacheSlots: {}, passesEligibilityCache: {}, @@ -162,21 +180,32 @@ describe('Claude profile refresh from the default home', () => { lastSeenOrgDefaultUpdatedAt: 1, hasAvailableSubscription: true, subscriptionNoticeCount: 2 - }) + } + f.json(join(f.userHome, '.claude.json'), personal) expect((await provision(f)).surfaces['.claude.json']).toBe('synced') - expect(f.read(join(f.profileHome, '.claude.json'))).toEqual({ - ...shared, - groveChoiceSeenAt: { 'account-a': 99, 'account-b': 10 } - }) + expect(f.read(join(f.profileHome, '.claude.json'))).toEqual(shared) expect(fs.readdirSync(f.profileHome).filter((name) => name.endsWith('.tmp'))).toEqual([]) expect(fs.existsSync(join(f.profileHome, '.credentials.json'))).toBe(false) fs.writeFileSync(join(f.profileHome, '.credentials.json'), 'PROFILE_CREDENTIAL_BYTES') + const profileRuntime = { + groveChoiceSeenAt: { profile: 20 }, + numStartups: 30, + tipsHistory: { tip: 8 }, + seenNotifications: { profileNotice: 9 }, + penguinModeOrgEnabled: true, + futureRuntimeState: { profile: true }, + customApiKeyResponses: { + approved: ['PROFILE_APPROVED_SUFFIX', 'PERSONAL_REJECTED_SUFFIX'], + rejected: ['PROFILE_REJECTED_SUFFIX', 'PERSONAL_APPROVED_SUFFIX'], + profileOnly: true + } + } f.json(join(f.profileHome, '.claude.json'), { + ...profileRuntime, oauthAccount: { emailAddress: 'profile@example.com' }, userID: 'profile-id', groveConfigCache: { b: 2 }, - groveChoiceSeenAt: { 'account-a': 120, 'account-b': 5 }, theme: 'light', onlyHere: true }) @@ -185,11 +214,30 @@ describe('Claude profile refresh from the default home', () => { oauthAccount: { emailAddress: 'profile@example.com' }, userID: 'profile-id', groveConfigCache: { b: 2 }, - groveChoiceSeenAt: { 'account-a': 120, 'account-b': 10 }, onlyHere: true, - ...shared + ...shared, + ...profileRuntime, + hasCompletedOnboarding: true, + customApiKeyResponses: { + approved: ['PROFILE_APPROVED_SUFFIX', 'PERSONAL_REJECTED_SUFFIX'], + rejected: [ + 'PROFILE_REJECTED_SUFFIX', + 'PERSONAL_APPROVED_SUFFIX', + 'PERSONAL_REJECTED_SUFFIX' + ], + profileOnly: true + } + }) + const reset = { ...f.read(join(f.profileHome, '.claude.json')), hasCompletedOnboarding: false } + f.json(join(f.profileHome, '.claude.json'), reset) + f.json(join(f.userHome, '.claude.json'), { + ...personal, + numStartups: 1000, + groveChoiceSeenAt: { personal: 1000 }, + futureRuntimeState: { changed: true } }) expect((await provision(f)).surfaces['.claude.json']).toBe('unchanged') + expect(f.read(join(f.profileHome, '.claude.json'))).toEqual(reset) expect(fs.readFileSync(join(f.source, '.credentials.json'), 'utf8')).toBe( 'SOURCE_CREDENTIAL_BYTES' ) @@ -202,7 +250,13 @@ describe('Claude profile refresh from the default home', () => { const f = fixture() f.json(join(f.userHome, '.claude.json'), { projects: { - '/shared': { hasTrustDialogAccepted: false, allowedTools: ['Read'] }, + '/shared': { + hasTrustDialogAccepted: false, + allowedTools: ['Read'], + lastSessionId: 'personal' + }, + '/runtime-only': { lastSessionId: 'personal' }, + '/malformed': 'invalid', '/default-only': { hasTrustDialogAccepted: true } }, mcpServers: { shared: { command: 'default' } } @@ -210,7 +264,15 @@ describe('Claude profile refresh from the default home', () => { f.json(join(f.profileHome, '.claude.json'), { oauthAccount: LOGIN, projects: { - '/shared': { hasTrustDialogAccepted: true }, + '/shared': { + hasTrustDialogAccepted: true, + hasCompletedProjectOnboarding: true, + projectOnboardingSeenCount: 4, + lastSessionId: 'profile', + exampleFiles: ['profile.ts'], + futureProjectState: true + }, + '/malformed': { lastSessionId: 'keep' }, '/account-only': { hasTrustDialogAccepted: true, allowedTools: ['Bash'] } }, mcpServers: { shared: { command: 'account' }, mine: { command: 'mine' } } @@ -219,7 +281,16 @@ describe('Claude profile refresh from the default home', () => { expect(f.read(join(f.profileHome, '.claude.json'))).toEqual({ oauthAccount: LOGIN, projects: { - '/shared': { hasTrustDialogAccepted: true, allowedTools: ['Read'] }, + '/shared': { + hasTrustDialogAccepted: true, + allowedTools: ['Read'], + hasCompletedProjectOnboarding: true, + projectOnboardingSeenCount: 4, + lastSessionId: 'profile', + exampleFiles: ['profile.ts'], + futureProjectState: true + }, + '/malformed': { lastSessionId: 'keep' }, '/account-only': { hasTrustDialogAccepted: true, allowedTools: ['Bash'] }, '/default-only': { hasTrustDialogAccepted: true } }, diff --git a/src/main/claude-accounts/claude-profile-provisioning.ts b/src/main/claude-accounts/claude-profile-provisioning.ts index ffd28dbb913..42bcdd1a8e5 100644 --- a/src/main/claude-accounts/claude-profile-provisioning.ts +++ b/src/main/claude-accounts/claude-profile-provisioning.ts @@ -19,6 +19,7 @@ import { type ClaudeProfileSurfaceOutcome } from './claude-profile-report' import { syncClaudeProfileSettings } from './claude-profile-settings' +import { mergeClaudeProfileState, selectSharedClaudeProfileState } from './claude-profile-state' import { copyClaudeProfileFile, linkClaudeProfileDirectory } from './claude-profile-sharing' const CLAUDE_PROFILE_MEMORY_IMPORT = '@~/.claude/CLAUDE.md\n' @@ -108,88 +109,6 @@ function isSharedEntry(name: string): boolean { ) } -// Claude 2.1.295 logout keys and subscription notices; onboarding remains shareable. -const CLAUDE_LOGOUT_STATE_KEYS = [ - 'oauthAccount', - 'additionalModelOptionsCache', - 'additionalModelOptionsAnsweredAt', - 'additionalModelCostsCache', - 'modelAccessCache', - 'orgModelDefaultCache', - 'cachedArtifactRoster', - 'artifactRosterDenied', - 'lastSeenOrgDefaultUpdatedAt', - 'clientDataCache', - 'clientDataCacheSlots', - 'autoCompactWindowsCache', - 'cachedUsageUtilization', - 'metricsStatusCache', - 'metricsStatusCacheByPrincipal', - 'githubWebConnectionStatusCache', - 'startupPrefetchedAt', - 'subscriptionNoticeCount', - 'hasAvailableSubscription' -] as const - -const ACCOUNT_BOUND_STATE_KEYS: ReadonlySet = new Set([ - ...CLAUDE_LOGOUT_STATE_KEYS, - 'userID', - 'machineID', - 'firstStartTime', - 'firstStartVersion', - // A copied Console key would override the account's own login. - 'primaryApiKey', - // Claude never refetches this account-specific date. - 'claudeCodeFirstTokenDate' -]) - -function isAccountBoundState(key: string): boolean { - // Logout leaves additional account caches such as groveConfigCache and passes*. - return ( - ACCOUNT_BOUND_STATE_KEYS.has(key) || - key.includes('Cache') || - key.startsWith('cached') || - key.startsWith('passes') - ) -} - -// Merge per entry so a profile keeps its own projects, servers, and Grove confirmations. -const MERGED_BY_ENTRY: ReadonlySet = new Set([ - 'projects', - 'mcpServers', - 'groveChoiceSeenAt' -]) - -function isPlainRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - -function mergeEntries(key: string, current: unknown, source: unknown): unknown { - if (!isPlainRecord(current) || !isPlainRecord(source)) { - return source - } - const merged: Record = { ...current, ...source } - if (key === 'projects') { - for (const [path, entry] of Object.entries(source)) { - const own = current[path] - // Preserve trust granted in this account, including just before launch. - if (isPlainRecord(own) && own.hasTrustDialogAccepted === true && isPlainRecord(entry)) { - merged[path] = { ...entry, hasTrustDialogAccepted: true } - } - } - } - if (key === 'groveChoiceSeenAt') { - // Claude trusts a confirmation only while it is fresh, so keep each account's newest one. - for (const [account, seenAt] of Object.entries(current)) { - const theirs = source[account] - if (typeof seenAt === 'number' && (typeof theirs !== 'number' || seenAt > theirs)) { - merged[account] = seenAt - } - } - } - return merged -} - async function copyState(source: string, target: string): Promise { if (lstatIfPresent(target)?.isSymbolicLink()) { return 'user-owned' @@ -201,11 +120,11 @@ async function copyState(source: string, target: string): Promise !isAccountBoundState(key)) + const shared = selectSharedClaudeProfileState(input.value) if (!lstatIfPresent(target)) { const staged = `${target}.${process.pid}.${randomUUID()}.tmp` try { - writeFileSync(staged, `${JSON.stringify(Object.fromEntries(shared), null, 2)}\n`, { + writeFileSync(staged, `${JSON.stringify(mergeClaudeProfileState({}, shared), null, 2)}\n`, { flag: 'wx', mode: 0o600 }) @@ -219,10 +138,7 @@ async function copyState(source: string, target: string): Promise { - const config = { ...current } - for (const [key, value] of shared) { - config[key] = MERGED_BY_ENTRY.has(key) ? mergeEntries(key, current[key], value) : value - } + const config = mergeClaudeProfileState(current, shared) return JSON.stringify(config) === JSON.stringify(current) ? { kind: 'unchanged' } : { kind: 'changed', config } diff --git a/src/main/claude-accounts/claude-profile-state.ts b/src/main/claude-accounts/claude-profile-state.ts new file mode 100644 index 00000000000..52cf971041a --- /dev/null +++ b/src/main/claude-accounts/claude-profile-state.ts @@ -0,0 +1,172 @@ +// Unknown state belongs to the profile; only deliberate user configuration is shared. +const SHARED_CONFIG_KEYS = [ + 'apiKeyHelper', + 'installMethod', + 'autoUpdates', + 'autoUpdatesProtectedForNative', + 'theme', + 'verbose', + 'preferredNotifChannel', + 'shiftEnterKeyBindingInstalled', + 'editorMode', + 'hasUsedBackslashReturn', + 'autoCompactEnabled', + 'autoScrollEnabled', + 'showTurnDuration', + 'externalEditorContext', + 'showMessageTimestamps', + 'diffTool', + 'env', + 'todoFeatureEnabled', + 'showExpandedTodos', + 'briefTranscript', + 'diffSidebarOpen', + 'messageIdleNotifThresholdMs', + 'autoConnectIde', + 'autoInstallIdeExtension', + 'fileCheckpointingEnabled', + 'terminalProgressBarEnabled', + 'showStatusInTerminalTab', + 'taskCompleteNotifEnabled', + 'inputNeededNotifEnabled', + 'agentPushNotifEnabled', + 'respectGitignore', + 'claudeInChromeDefaultEnabled', + 'hasCompletedClaudeInChromeOnboarding', + 'lspRecommendationDisabled', + 'lspRecommendationNeverPlugins', + 'copyFullResponse', + 'copyOnSelect', + 'leftArrowOpensAgents', + 'defaultToAgentsView', + 'prStatusFooterEnabled', + 'remoteControlAtStartup', + 'autoUploadSessions', + 'autoAddRemoteControlDaemonWorker', + 'remoteDialogSeen', + 'workflowSizeGuideline', + 'favoritePlugins', + 'preferTmuxOverIterm2', + 'codeReviewLastEffort', + 'codeReviewLastMaxFindings', + 'bypassPermissionsModeAccepted', + 'mcpServers' +] as const + +const SHARED_PROJECT_KEYS = [ + 'allowedTools', + 'mcpContextUris', + 'mcpServers', + 'enabledMcpjsonServers', + 'disabledMcpjsonServers', + 'hasClaudeMdExternalIncludesApproved', + 'hasTrustDialogAccepted' +] as const + +function isPlainRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function selectConfigFields( + source: Record, + keys: readonly string[] +): Record { + return Object.fromEntries( + keys.filter((key) => Object.hasOwn(source, key)).map((key) => [key, source[key]]) + ) +} + +export function selectSharedClaudeProfileState( + source: Record +): Record { + const shared = selectConfigFields(source, SHARED_CONFIG_KEYS) + if (isPlainRecord(source.projects)) { + const projects: Record = {} + for (const [path, entry] of Object.entries(source.projects)) { + if (isPlainRecord(entry)) { + const selected = selectConfigFields(entry, SHARED_PROJECT_KEYS) + if (Object.keys(selected).length > 0) { + projects[path] = selected + } + } + } + if (Object.keys(projects).length > 0) { + shared.projects = projects + } + } + if (source.hasCompletedOnboarding === true) { + shared.hasCompletedOnboarding = true + } + if ( + isPlainRecord(source.customApiKeyResponses) && + Array.isArray(source.customApiKeyResponses.rejected) + ) { + const rejected = source.customApiKeyResponses.rejected.filter( + (value) => typeof value === 'string' + ) + if (rejected.length > 0) { + shared.customApiKeyResponses = { rejected } + } + } + return shared +} + +function mergeProjects(current: unknown, source: Record): unknown { + if (current !== undefined && !isPlainRecord(current)) { + return current + } + const projects: Record = { ...current } + for (const [path, entry] of Object.entries(source)) { + const own = projects[path] + if (isPlainRecord(entry) && (own === undefined || isPlainRecord(own))) { + projects[path] = { + ...own, + ...entry, + ...(own?.hasTrustDialogAccepted === true ? { hasTrustDialogAccepted: true } : {}) + } + } + } + return projects +} + +function mergeRejectedApiKeys(current: unknown, source: Record): unknown { + if (current !== undefined && !isPlainRecord(current)) { + return current + } + const previous = current?.rejected + if ((previous !== undefined && !Array.isArray(previous)) || !Array.isArray(source.rejected)) { + return current + } + const rejected = [...(previous ?? [])] + const seen = new Set(rejected) + for (const value of source.rejected) { + if (!seen.has(value)) { + seen.add(value) + rejected.push(value) + } + } + return { ...current, rejected } +} + +export function mergeClaudeProfileState( + current: Record, + shared: Record +): Record { + const config = { ...current } + for (const [key, value] of Object.entries(shared)) { + if (key === 'hasCompletedOnboarding') { + if (!Object.hasOwn(current, key)) { + config[key] = true + } + } else if (key === 'customApiKeyResponses' && isPlainRecord(value)) { + config[key] = mergeRejectedApiKeys(current[key], value) + } else if (key === 'projects' && isPlainRecord(value)) { + config[key] = mergeProjects(current[key], value) + } else if (key === 'mcpServers' && isPlainRecord(current[key]) && isPlainRecord(value)) { + config[key] = { ...current[key], ...value } + } else { + config[key] = value + } + } + return config +} diff --git a/src/main/claude/claude-rejected-api-key.test.ts b/src/main/claude/claude-rejected-api-key.test.ts new file mode 100644 index 00000000000..be29004e40c --- /dev/null +++ b/src/main/claude/claude-rejected-api-key.test.ts @@ -0,0 +1,40 @@ +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { withoutRejectedClaudeApiKey } from './claude-rejected-api-key' + +it('honors profile approval ahead of a shared rejection, while dropping rejected-only keys', async () => { + const home = mkdtempSync(join(tmpdir(), 'claude-api-key-')) + const config = join(home, 'claude') + mkdirSync(config) + const env = { + HOME: home, + CLAUDE_CONFIG_DIR: config, + ANTHROPIC_API_KEY: 'fixture-prefix-0123456789abcdefghij' + } + try { + writeFileSync( + join(config, '.claude.json'), + JSON.stringify({ + customApiKeyResponses: { + approved: ['0123456789abcdefghij'], + rejected: ['0123456789abcdefghij'] + } + }) + ) + expect(await withoutRejectedClaudeApiKey({ ...env })).toEqual(env) + writeFileSync( + join(config, '.claude.json'), + JSON.stringify({ + customApiKeyResponses: { approved: [], rejected: ['0123456789abcdefghij'] } + }) + ) + expect(await withoutRejectedClaudeApiKey({ ...env })).toEqual({ + HOME: home, + CLAUDE_CONFIG_DIR: config + }) + } finally { + rmSync(home, { recursive: true, force: true }) + } +}) diff --git a/src/main/claude/claude-rejected-api-key.ts b/src/main/claude/claude-rejected-api-key.ts index 38c61451579..d9afa94d907 100644 --- a/src/main/claude/claude-rejected-api-key.ts +++ b/src/main/claude/claude-rejected-api-key.ts @@ -3,19 +3,27 @@ import { readFile } from 'node:fs/promises' import { homedir } from 'node:os' import { resolveClaudeGlobalConfigFile } from './claude-folder-trust-file' -async function readRejectedApiKeyIds(configFile: string): Promise { +type ClaudeApiKeyResponses = { approved: readonly unknown[]; rejected: readonly unknown[] } + +async function readApiKeyResponses(configFile: string): Promise { + const empty = { approved: [], rejected: [] } try { const parsed: unknown = JSON.parse(await readFile(configFile, 'utf8')) if (typeof parsed !== 'object' || parsed === null || !('customApiKeyResponses' in parsed)) { - return [] + return empty } const responses = parsed.customApiKeyResponses - if (typeof responses !== 'object' || responses === null || !('rejected' in responses)) { - return [] + if (typeof responses !== 'object' || responses === null) { + return empty + } + return { + approved: + 'approved' in responses && Array.isArray(responses.approved) ? responses.approved : [], + rejected: + 'rejected' in responses && Array.isArray(responses.rejected) ? responses.rejected : [] } - return Array.isArray(responses.rejected) ? responses.rejected : [] } catch { - return [] + return empty } } @@ -38,9 +46,10 @@ export async function withoutRejectedClaudeApiKey( style, exists: existsSync }) - const rejected = await readRejectedApiKeyIds(configFile) + const responses = await readApiKeyResponses(configFile) // Claude records answers by the trimmed key's last 20 characters. - if (rejected.includes(apiKey.trim().slice(-20))) { + const suffix = apiKey.trim().slice(-20) + if (!responses.approved.includes(suffix) && responses.rejected.includes(suffix)) { for (const name of keyNames) { delete env[name] } diff --git a/src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts b/src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts index 3fe0e337ea9..3d6b9c7ade2 100644 --- a/src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts +++ b/src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts @@ -55,58 +55,62 @@ it.each(['saved', 'recover'] as const)( ) describe('codex model catalog probe', () => { - it.each([[[]]])( - "lists a command line with arguments %j from Orca's folder for every chat", - async (prefixArgs) => { - // The chat's repo never picks the list, so no listing runs in a chat's folder. - const invocations: CodexAppServerInvocation[] = [] - const configReads: unknown[] = [] - const probe = createCodexModelCatalogProbe({ - resolveEnvironment: async () => ({ PATH: '/bin' }), - resolveCommand: () => ({ command: '/bin/codex', prefixArgs }), - runSession: async (invocation, body) => { - invocations.push(invocation) - return body({ - request: async (method: string, params: unknown) => { - if (method === 'config/read') { - configReads.push(params) - return { config: {} } - } - return { data: [MODEL_ROW], nextCursor: null } - }, - notify: () => {} - }) - } - }) - const identities: unknown[] = [] - for (const folder of ['/chat-a', '/chat-b']) { - const resolved = await probe.resolve?.( - { variable: 'CODEX_HOME', path: '/homes/a' }, - '/orca-probe', - 'snapshot', - undefined, - folder - ) - identities.push(resolved?.identity) - await resolved?.run() + it.each([ + [[], ['/orca-probe', '/orca-probe']], + [['node_modules/@openai/codex/bin/codex.js'], ['/chat-a', '/chat-b']], + [ + ['-c', 'model_instructions_file="./prompt.md"'], + ['/chat-a', '/chat-b'] + ] + ])('lists a command line with arguments %j from %j', async (prefixArgs, listedIn) => { + // Only the plain CLI shares one listing; user arguments may name files in the chat's folder. + const invocations: CodexAppServerInvocation[] = [] + const configReads: unknown[] = [] + const probe = createCodexModelCatalogProbe({ + resolveEnvironment: async () => ({ PATH: '/bin' }), + resolveCommand: () => ({ command: '/bin/codex', prefixArgs }), + runSession: async (invocation, body) => { + invocations.push(invocation) + return body({ + request: async (method: string, params: unknown) => { + if (method === 'config/read') { + configReads.push(params) + return { config: {} } + } + return { data: [MODEL_ROW], nextCursor: null } + }, + notify: () => {} + }) } - expect(invocations.map((invocation) => invocation.cwd)).toEqual([ + }) + const identities: unknown[] = [] + for (const folder of ['/chat-a', '/chat-b']) { + const resolved = await probe.resolve?.( + { variable: 'CODEX_HOME', path: '/homes/a' }, '/orca-probe', - '/orca-probe' - ]) - expect(invocations[0]?.args.slice(0, prefixArgs.length + 2)).toEqual([ - ...prefixArgs, - '-c', - 'project_root_markers=[]' - ]) - expect(identities[0]).toMatchObject({ cwd: '/orca-probe' }) - expect(identities[1]).toEqual(identities[0]) - // The account's configured default is read for Orca's folder, never the project's. - expect(configReads).toEqual( - expect.arrayContaining([expect.objectContaining({ cwd: '/orca-probe' })]) + 'snapshot', + undefined, + folder ) + identities.push(resolved?.identity) + await resolved?.run() } - ) + expect(invocations.map((invocation) => invocation.cwd)).toEqual(listedIn) + expect(invocations[0]?.args.slice(0, prefixArgs.length)).toEqual(prefixArgs) + // A listing in the chat's folder never loads that folder's project config. + expect(invocations[0]?.args.includes('projects={"/chat-a"={trust_level="untrusted"}}')).toBe( + listedIn[0] === '/chat-a' + ) + expect(invocations[0]?.args).toContain('project_root_markers=[]') + expect(identities[0]).toMatchObject({ cwd: listedIn[0] }) + expect(JSON.stringify(identities[0]) === JSON.stringify(identities[1])).toBe( + listedIn[0] === listedIn[1] + ) + // The account's configured default is read for Orca's folder, never the project's. + expect(configReads).toEqual( + expect.arrayContaining([expect.objectContaining({ cwd: '/orca-probe' })]) + ) + }) it('keeps the listing when config/read never answers', async () => { const server = String.raw` 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 fe4b82a24a2..94c26ee190c 100644 --- a/src/main/codex/structured/catalog/codex-model-catalog-probe.ts +++ b/src/main/codex/structured/catalog/codex-model-catalog-probe.ts @@ -4,13 +4,17 @@ import { } from '../../../native-chat/structured-agent-command-resolution' import { codexStructuredLaunchArgs } from '../launch/codex-structured-launch-args' import { overlayEnvironmentVariables } from '../../../../shared/environment-overlay' -import { envWithPathRelativeTo } from '../../../../shared/node-cli-command-resolution' +import { + catalogListingDirectory, + envWithPathRelativeTo +} from '../../../../shared/node-cli-command-resolution' import type { AgentSessionAccountKind } from '../../../../shared/agent-session/agent-session-availability' import { AgentModelCatalogUnavailableError } from '../../../native-chat/agent-model-catalog/agent-model-catalog-unavailable' import { isMissingProviderExecutable } from '../../../provider-process/provider-executable-missing' import { CODEX_SHORT_LIVED_PROBE_APP_SERVER_ARGS } from '../../../codex-cli/codex-read-only-app-server-args' import { runCodexAppServerSession } from '../../app-server/codex-app-server-session' import { fetchCodexModelCatalogListing } from './codex-structured-model-catalog' +import { codexProjectConfigIsolationArgs } from './codex-project-config-isolation' import { applyCodexConfiguredLaunchDefaults } from '../launch/codex-configured-launch-defaults' import { resolveCodexStructuredInvocation, @@ -70,13 +74,17 @@ export function createCodexModelCatalogProbe( ...(launchDirectory ? { resolveWorkingDirectory: () => launchDirectory } : {}) }) assertStructuredAgentResolutionCurrent(operation) - // Every listing runs in `cwd` with the user's command line, as other Codex hosts list from their - // own folder, so the chat's repo never picks the list; relative paths in user arguments are not - // resolved against the chat's folder. No root markers keep Codex from reading a repo above - // Orca's folder too, unless an administrator's managed config sets its own. - const args = [ + const userArgs = [ ...prefixArgs, - ...(cwd ? codexStructuredLaunchArgs((await deps.resolveLaunchArgs?.()) ?? []) : []), + ...(cwd ? codexStructuredLaunchArgs((await deps.resolveLaunchArgs?.()) ?? []) : []) + ] + // A command line that may name files relative to the chat's folder runs there, with that + // folder untrusted so its project config never replaces the account's list. No root markers + // keep Codex from reading a repo above the listing's folder, unless managed config sets its own. + const listIn = catalogListingDirectory(command, userArgs, cwd, launchDirectory) + const args = [ + ...userArgs, + ...(listIn && listIn !== cwd ? await codexProjectConfigIsolationArgs(listIn) : []), '-c', 'project_root_markers=[]', ...CODEX_SHORT_LIVED_PROBE_APP_SERVER_ARGS @@ -90,7 +98,7 @@ export function createCodexModelCatalogProbe( CODEX_HOME: accountHomePath } return { - identity: { command, args, cwd, overlay: Object.entries(overlay).sort() }, + identity: { command, args, cwd: listIn, overlay: Object.entries(overlay).sort() }, run: async ( signal?: AbortSignal, runOperation = operation @@ -103,7 +111,7 @@ export function createCodexModelCatalogProbe( { command, args, - ...(cwd ? { cwd } : {}), + ...(listIn ? { cwd: listIn } : {}), cliPath: command, env, timeoutMs: AGENT_MODEL_CATALOG_PROBE_TIMEOUT_MS, diff --git a/src/main/codex/structured/catalog/codex-project-config-isolation.test.ts b/src/main/codex/structured/catalog/codex-project-config-isolation.test.ts new file mode 100644 index 00000000000..56ea8b4d6bd --- /dev/null +++ b/src/main/codex/structured/catalog/codex-project-config-isolation.test.ts @@ -0,0 +1,12 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { codexProjectConfigIsolationArgs } from './codex-project-config-isolation' + +afterEach(() => vi.unstubAllGlobals()) + +it("also untrusts Windows Codex's lowercased key, which an exact saved entry would otherwise win", async () => { + vi.stubGlobal('process', { ...process, platform: 'win32' }) + expect(await codexProjectConfigIsolationArgs('C:\\Users\\Ärla\\Repo')).toEqual([ + '-c', + 'projects={"C:\\\\Users\\\\Ärla\\\\Repo"={trust_level="untrusted"},"c:\\\\users\\\\Ärla\\\\repo"={trust_level="untrusted"}}' + ]) +}) diff --git a/src/main/codex/structured/catalog/codex-project-config-isolation.ts b/src/main/codex/structured/catalog/codex-project-config-isolation.ts new file mode 100644 index 00000000000..07d197e13d1 --- /dev/null +++ b/src/main/codex/structured/catalog/codex-project-config-isolation.ts @@ -0,0 +1,18 @@ +import { realpath } from 'node:fs/promises' + +/** `-c` arguments that keep Codex from loading `dir`'s project config, so a listing that must run + * there still reports only the account's catalog. Needs `project_root_markers=[]` so no folder + * above `dir` is read. Override keys split on dots, so the folders go in the value. A managed + * config that trusts the folder still wins. */ +export async function codexProjectConfigIsolationArgs(dir: string): Promise { + const real = await realpath(dir).catch(() => dir) + // Windows Codex tries an ASCII-lowercased key first; a saved "trusted" one would win. + const spellings = + process.platform === 'win32' + ? [dir, real].map((folder) => folder.replace(/[A-Z]/g, (letter) => letter.toLowerCase())) + : [] + const table = [...new Set([dir, real, ...spellings])] + .map((folder) => `${JSON.stringify(folder)}={trust_level="untrusted"}`) + .join(',') + return ['-c', `projects={${table}}`] +} diff --git a/src/main/codex/structured/items/codex-image-item-translation.test.ts b/src/main/codex/structured/items/codex-image-item-translation.test.ts new file mode 100644 index 00000000000..5a3f0ca6594 --- /dev/null +++ b/src/main/codex/structured/items/codex-image-item-translation.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest' +import type { NativeChatMessage } from '../../../../shared/native-chat/native-chat-types' +import { + nativeChatTurnFold, + nativeChatTurnFoldRow +} from '../../../../shared/native-chat/transcript/native-chat-turn-fold' +import { codexImageItemBody } from './codex-image-item-translation' + +function row(id: string, role: NativeChatMessage['role'], blocks: NativeChatMessage['blocks']) { + const message: NativeChatMessage = { id, role, blocks, timestamp: 1, source: 'transcript' } + return nativeChatTurnFoldRow(message, 'turn-1', false) +} + +function settledFold(imageItem: Record): number[] { + const image = codexImageItemBody({ id: 'image', ...imageItem, type: String(imageItem.type) }) + if (image.kind !== 'message') { + throw new Error('expected a message row') + } + const rows = [ + row('prompt', 'user', [{ type: 'text', text: 'Generate an elephant image' }]), + row('image', 'assistant', image.blocks), + row('answer', 'assistant', [{ type: 'text', text: 'Generated a realistic elephant.' }]) + ] + const fold = nativeChatTurnFold({ + rows, + settledTurnKeys: new Set(['turn-1']), + expandedTurnKeys: new Set() + }) + return [...fold.foldedRows] +} + +describe('Codex image rows in a settled turn', () => { + it('keeps a generated image visible beside the answer', () => { + expect( + settledFold({ + type: 'imageGeneration', + status: 'completed', + savedPath: 'C:\\Users\\me\\.codex\\generated_images\\thread\\exec-1.png' + }) + ).toEqual([]) + }) + + it('folds an image the agent only viewed', () => { + expect(settledFold({ type: 'imageView', path: '/tmp/screenshot.png' })).toEqual([1]) + }) +}) diff --git a/src/main/codex/structured/items/codex-image-item-translation.ts b/src/main/codex/structured/items/codex-image-item-translation.ts index abbc6ae5308..524e6c8fc46 100644 --- a/src/main/codex/structured/items/codex-image-item-translation.ts +++ b/src/main/codex/structured/items/codex-image-item-translation.ts @@ -1,6 +1,7 @@ import type { AgentJournalMessageItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' import type { NativeChatBlock } from '../../../../shared/native-chat/native-chat-types' import { buildImageDataUri } from '../../../../shared/file-preview/image-data-uri' +import { NATIVE_CHAT_GENERATED_IMAGE_PRESENTATION } from '../../../../shared/native-chat/native-chat-generated-image' import { readString } from '../../app-server/codex-item-field-readers' import type { CodexThreadItem } from './codex-thread-item-identity' @@ -31,6 +32,7 @@ export function generatedImageUrl(item: CodexThreadItem): string | null { export function codexImageItemBody(item: CodexThreadItem): AgentJournalMessageItem { let image: Extract | null = null let text: string + let presentation: string | undefined if (item.type === 'imageView') { const path = imagePath(item, 'path') text = path ? 'Viewed image' : 'Image view: preview unavailable' @@ -54,11 +56,15 @@ export function codexImageItemBody(item: CodexThreadItem): AgentJournalMessageIt ? { type: 'image-ref', url, alt: 'Generated image' } : null text = image ? 'Generated image' : 'Image generated: preview unavailable' + presentation = image ? NATIVE_CHAT_GENERATED_IMAGE_PRESENTATION : undefined } } return { kind: 'message', role: 'assistant', - blocks: [{ type: 'text', text }, ...(image ? [image] : [])] + blocks: [ + { type: 'text', text, ...(presentation ? { presentation } : {}) }, + ...(image ? [image] : []) + ] } } diff --git a/src/main/codex/structured/journal/codex-turn-failures.test.ts b/src/main/codex/structured/journal/codex-turn-failures.test.ts index 9a89ea774a8..96bf3377025 100644 --- a/src/main/codex/structured/journal/codex-turn-failures.test.ts +++ b/src/main/codex/structured/journal/codex-turn-failures.test.ts @@ -31,37 +31,6 @@ function statuses(tap: ReturnType) { } describe('Codex terminal failure categories', () => { - it.each([ - ['rateLimitExceeded', 'usageLimitReached'], - ['flexUnavailable', 'providerUnavailable'], - ['modelNotFound', 'modelUnavailable'], - ['policyCapacityUnavailable', 'providerUnavailable'], - ['misalignmentPolicyViolation', 'providerSafetyStopped'], - ['serverOverloaded', 'providerUnavailable'], - ['cyberPolicy', 'providerSafetyStopped'] - ])('categorizes %s without exposing its diagnostic', (code, kind) => { - for (const info of [code, { [code]: { httpStatusCode: 401 } }]) { - const tap = recorder() - const translator = translatorFor(tap) - translator.handle(notification('error', error(info))) - expect(statuses(tap)).toMatchObject([{ failure: { kind } }]) - expect(statuses(tap)[0]?.text).not.toContain(DIAGNOSTIC) - expect(statuses(tap)[0]?.providerFrame?.payload.head).toContain(DIAGNOSTIC) - translator.dispose() - } - }) - - it('uses the existing usage-limit category for HTTP 429 retry exhaustion', () => { - const tap = recorder() - const translator = translatorFor(tap) - translator.handle( - notification('error', error({ responseTooManyFailedAttempts: { httpStatusCode: 429 } })) - ) - expect(statuses(tap)).toMatchObject([ - { tone: 'warning', failure: { kind: 'usageLimitReached' } } - ]) - }) - it('ends a recorded-shape failed completion carrying an unknown future code', () => { const frames: { case: string 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 82aeeae47b2..3e6cc7fc1e4 100644 --- a/src/main/codex/structured/launch/codex-structured-launch-resolution.ts +++ b/src/main/codex/structured/launch/codex-structured-launch-resolution.ts @@ -29,6 +29,8 @@ import type { StructuredAgentLaunchPartResolver } from '../../../runtime/agent-s import type { CodexStructuredLaunch } from '../session-lifecycle/codex-structured-session-state' import { codexStructuredPermissionPolicy } from '../../../../shared/codex-permission-policy' import { codexStructuredLaunchArgs } from './codex-structured-launch-args' +import { codexOrcaHooksOffArgs } from './codex-structured-orca-hooks-off' +import { getSystemCodexHomePath } from '../../configuration/homes/codex-home-paths' import { LEGACY_NATIVE_CHAT_VISUALS_DIR_ENV, NATIVE_CHAT_SCRATCH_DIR_ENV, @@ -160,7 +162,15 @@ export function codexStructuredLaunchPart( launch: { command, prefixArgs, - args: [...prefixArgs, ...args, 'app-server'], + // Before the user's args: a later -c table replaces this one, so their hooks.state wins. + args: [ + ...prefixArgs, + ...codexOrcaHooksOffArgs( + accountHome.path || environment?.CODEX_HOME || getSystemCodexHomePath() + ), + ...args, + 'app-server' + ], codexHome: accountHome.path, resumeThreadId, // Only created threads may be unsaved; resumed, forked and adopted threads were persisted. diff --git a/src/main/codex/structured/launch/codex-structured-orca-hooks-off.test.ts b/src/main/codex/structured/launch/codex-structured-orca-hooks-off.test.ts new file mode 100644 index 00000000000..79ef1086154 --- /dev/null +++ b/src/main/codex/structured/launch/codex-structured-orca-hooks-off.test.ts @@ -0,0 +1,41 @@ +import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { buildCodexHookCommand } from '../../hooks/definitions/codex-hook-command-form' +import { getManagedScriptPath } from '../../hooks/definitions/codex-hook-definition' +import { codexOrcaHooksOffArgs } from './codex-structured-orca-hooks-off' + +let home = '' +afterEach(() => rmSync(home, { recursive: true, force: true })) + +// Expected keys spell a POSIX home. +it.skipIf(process.platform === 'win32')( + "disables Orca's Codex hook entries for the launch and leaves the user's hooks enabled", + () => { + home = realpathSync(mkdtempSync(join(tmpdir(), 'orca-codex-hooks-off-'))) + const orca = { type: 'command', command: buildCodexHookCommand(getManagedScriptPath()) } + const olderOrca = { + type: 'command', + command: '/bin/sh "$HOME/.orca/agent-hooks/codex-hook.sh"' + } + const user = { type: 'command', command: 'echo user-hook' } + writeFileSync( + join(home, 'hooks.json'), + JSON.stringify({ + hooks: { + PreToolUse: [ + null, + { hooks: [user, null, { type: 'command', command: ['sh'] }, olderOrca] } + ], + PostToolUse: [{ hooks: [user, orca] }] + } + }) + ) + + expect(codexOrcaHooksOffArgs(home)).toEqual([ + '-c', + `hooks.state={"${home}/hooks.json:pre_tool_use:1:3"={enabled=false},"${home}/hooks.json:post_tool_use:0:1"={enabled=false}}` + ]) + } +) diff --git a/src/main/codex/structured/launch/codex-structured-orca-hooks-off.ts b/src/main/codex/structured/launch/codex-structured-orca-hooks-off.ts new file mode 100644 index 00000000000..7e0bc0e370b --- /dev/null +++ b/src/main/codex/structured/launch/codex-structured-orca-hooks-off.ts @@ -0,0 +1,44 @@ +import { createManagedCommandMatcher } from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import { readHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-read' +import { escapeTomlBasicString } from '../../configuration/toml/config-toml-syntax' +import { + createCodexHookTrustEntry, + getCodexManagedScriptFileName +} from '../../hooks/definitions/codex-hook-identity' +import { getInPlaceCodexHookHome } from '../../trust/hooks/codex-hook-orca-approvals' +import { computeCodexTrustKey } from '../../trust/identity/codex-trust-identity' + +/** + * Chat strips pane env, so Orca's status hooks only cost a spawn per event, and under Store + * PowerShell every spawn fails (openai/codex#47810). Disable Orca's entries, including older + * forms the installer keeps, for this launch. One inline table because Codex splits `-c` keys + * on every dot, including the one in hooks.json. + */ +export function codexOrcaHooksOffArgs(codexHomePath: string): string[] { + const home = getInPlaceCodexHookHome(codexHomePath) + const isOrcaCommand = createManagedCommandMatcher(getCodexManagedScriptFileName()) + const hooks = readHooksJson(home.hooksJsonPath)?.hooks ?? {} + // hooks.json is user-editable; skip malformed groups and handlers as Codex does. + const entries = Object.entries(hooks).flatMap(([eventName, groups]) => + (Array.isArray(groups) ? groups : []).flatMap((group, groupIndex) => + (Array.isArray(group?.hooks) ? group.hooks : []).flatMap((hook, handlerIndex) => + hook && isOrcaCommand(hook.command) + ? home.keySourcePaths.flatMap((sourcePath) => { + const entry = createCodexHookTrustEntry( + sourcePath, + eventName, + groupIndex, + handlerIndex, + group, + hook + ) + return entry + ? [`"${escapeTomlBasicString(computeCodexTrustKey(entry))}"={enabled=false}`] + : [] + }) + : [] + ) + ) + ) + return entries.length > 0 ? ['-c', `hooks.state={${entries.join(',')}}`] : [] +} diff --git a/src/main/git/command-runner/gh-exec-file.ts b/src/main/git/command-runner/gh-exec-file.ts index dcc7a3c67d0..9eb9b7c973a 100644 --- a/src/main/git/command-runner/gh-exec-file.ts +++ b/src/main/git/command-runner/gh-exec-file.ts @@ -21,6 +21,7 @@ import { execFileCaptureToTermination } from './exec-file-capture' import { logHostedCliDeadlineKill } from './hosted-cli-deadline-log' import type { GitExecOptions } from './git-exec-options' import { argsLookIdempotent } from './gh-idempotency' +import { GhExecutableAbsenceBatch } from './gh-executable-absence-batch' import { applyGhHostToArgs, explicitGhHostname, explicitGhRepoHostname } from './gh-host-args' import { isGhBoundAccountError, resolveBoundGhExecEnv } from './gh-bound-account-env' import { @@ -178,6 +179,13 @@ export async function ghExecFileWithScopeAsync( if (lifetime) { await lifetime.waitPending(options.signal) } + const availability = GhExecutableAbsenceBatch.assertAvailable( + resolved, + boundEnv ?? options.env ?? process.env + ) + if (availability) { + await availability + } // gh may be a shim chain; terminate the whole tree so descendants cannot outlive the deadline. const { stdout, stderr } = await execFileCaptureToTermination( resolved.binary, @@ -198,6 +206,7 @@ export async function ghExecFileWithScopeAsync( if (lifetime) { await lifetime.waitPending(options.signal) } + GhExecutableAbsenceBatch.recordSuccess(resolved, boundEnv ?? options.env ?? process.env) return { // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Capture decodes stdout with the requested string encoding above. stdout: stdout as string, @@ -277,6 +286,11 @@ export async function ghExecFileWithScopeAsync( await sleep(delayMs, options.signal) continue } + await GhExecutableAbsenceBatch.recordMissing( + resolved, + boundEnv ?? options.env ?? process.env, + err + ) throw err } finally { lifetime?.seal() diff --git a/src/main/git/command-runner/gh-executable-absence-batch.ts b/src/main/git/command-runner/gh-executable-absence-batch.ts new file mode 100644 index 00000000000..a2362641c3a --- /dev/null +++ b/src/main/git/command-runner/gh-executable-absence-batch.ts @@ -0,0 +1,116 @@ +import { AsyncLocalStorage } from 'node:async_hooks' +import { stat } from 'node:fs/promises' +import path from 'node:path' +import { + isCommandOnLocalPath, + resolveSelectedLocalCommand +} from '../../ipc/command-path/command-path-resolver' +import type { ResolvedCommand } from './wsl-command-resolution' + +const currentBatch = new AsyncLocalStorage() +const batches = new Set() + +function searchScope(command: ResolvedCommand, env: NodeJS.ProcessEnv): string | null { + if (command.wsl || command.binary !== 'gh' || !command.cwd) { + return null + } + const pathKey = Object.keys(env).find((key) => + process.platform === 'win32' ? key.toLowerCase() === 'path' : key === 'PATH' + ) + const searchPath = pathKey ? env[pathKey] : undefined + if (!searchPath || searchPath.split(path.delimiter).some((entry) => !path.isAbsolute(entry))) { + return null + } + const extensions = Object.entries(env).find(([key]) => key.toLowerCase() === 'pathext')?.[1] + return JSON.stringify([process.platform, command.binary, searchPath, extensions]) +} + +/** A finite recovery batch shares only proved native executable absence, never API failures. */ +export class GhExecutableAbsenceBatch { + private readonly missing = new Map() + + constructor() { + batches.add(this) + } + + run(operation: () => Promise): Promise { + return currentBatch.run(this, operation) + } + + close(): void { + batches.delete(this) + this.missing.clear() + } + + static assertAvailable(command: ResolvedCommand, env: NodeJS.ProcessEnv): Promise | null { + const batch = currentBatch.getStore() + if (!batch?.missing.size) { + return null + } + const scope = searchScope(command, env) + if (!scope || !batch.missing.has(scope)) { + return null + } + if (resolveSelectedLocalCommand('gh', { env, cwd: command.cwd }) !== 'gh') { + batch.missing.delete(scope) + return null + } + if (process.platform === 'win32') { + // Windows searches each checkout before PATH; a peer may have its own executable. + const localEnv = Object.fromEntries( + Object.entries(env).filter(([key]) => key.toLowerCase() !== 'path') + ) + return isCommandOnLocalPath('gh', { + env: { ...localEnv, PATH: '' }, + cwd: command.cwd + }).then((found) => { + if (!found) { + throw batch.missing.get(scope) + } + }) + } + throw batch.missing.get(scope) + } + + static async recordMissing( + command: ResolvedCommand, + env: NodeJS.ProcessEnv, + error: unknown + ): Promise { + const batch = currentBatch.getStore() + const scope = batch && searchScope(command, env) + if ( + !batch || + !scope || + !error || + typeof error !== 'object' || + !('code' in error) || + error.code !== 'ENOENT' || + batch.missing.get(scope) === error + ) { + return + } + try { + if ( + command.cwd && + (await stat(command.cwd)).isDirectory() && + resolveSelectedLocalCommand('gh', { env, cwd: command.cwd }) === 'gh' && + !(await isCommandOnLocalPath('gh', { env, cwd: command.cwd })) && + batches.has(batch) + ) { + batch.missing.set(scope, error) + } + } catch { + // A missing cwd or unreadable search environment proves nothing about peer checkouts. + } + } + + static recordSuccess(command: ResolvedCommand, env: NodeJS.ProcessEnv): void { + const scope = batches.size && searchScope(command, env) + if (scope) { + for (const batch of batches) { + batch.missing.delete(scope) + } + } + } +} diff --git a/src/main/git/remotes/hosted-remote-url.ts b/src/main/git/remotes/hosted-remote-url.ts index 9f10984fa05..5361b6ffac4 100644 --- a/src/main/git/remotes/hosted-remote-url.ts +++ b/src/main/git/remotes/hosted-remote-url.ts @@ -1,4 +1,5 @@ import { normalizeForgeWebHost } from '../../../shared/git/remotes/git-remote-host-alias' +import { getPublicForgeProviderForHost } from '../../../shared/git/remotes/public-forge-host' // Scoped local fork of the hosted-git-info@9.0.3 behavior Orca used. // Keep only the provider parsing and file/commit URL construction needed by source links. @@ -23,14 +24,14 @@ const shorthandHosts: Record { + for (const remote of [ + 'git@ssh.github.com:team/repo.git', + 'ssh://git@altssh.gitlab.com:443/team/repo.git', + 'https://acme.ghe.com/team/repo.git' + ]) { + expect(parseGiteaRepoRef(remote)).toBeNull() + } + expect(parseGiteaRepoRef('https://codeberg.org/team/repo.git')).toMatchObject({ + owner: 'team', + repo: 'repo' + }) + expect(parseGiteaRepoRef('https://git.acme.test/team/repo.git')).toMatchObject({ + owner: 'team', + repo: 'repo' + }) +}) diff --git a/src/main/gitea/repository-ref.ts b/src/main/gitea/repository-ref.ts index 89162701eda..d5ed49c716b 100644 --- a/src/main/gitea/repository-ref.ts +++ b/src/main/gitea/repository-ref.ts @@ -1,4 +1,5 @@ import { createRemoteRefProbeCache } from '../git/remotes/remote-ref-probe-cache' +import { getPublicForgeProviderForHost } from '../../shared/git/remotes/public-forge-host' export type GiteaRepoRef = { host: string @@ -12,14 +13,6 @@ type LocalGitExecOptions = { wslDistro?: string } -const KNOWN_NON_GITEA_HOSTS = new Set([ - 'github.com', - 'gitlab.com', - 'bitbucket.org', - 'ssh.bitbucket.org', - 'dev.azure.com', - 'ssh.dev.azure.com' -]) const repoRefProbeCache = createRemoteRefProbeCache(parseGiteaRepoRef) /** @internal - exposed for tests only */ @@ -69,11 +62,8 @@ function apiBaseUrlFromWebBase(webBaseUrl: string): string { function makeRepoRef(host: string, path: string, webOrigin: string): GiteaRepoRef | null { const normalizedHost = host.toLowerCase() - if ( - !normalizedHost || - KNOWN_NON_GITEA_HOSTS.has(normalizedHost) || - normalizedHost.endsWith('.visualstudio.com') - ) { + const owner = getPublicForgeProviderForHost(normalizedHost) + if (!normalizedHost || (owner && owner !== 'gitea')) { return null } diff --git a/src/main/github/client/fetch/repo-slug-upstream.ts b/src/main/github/client/fetch/repo-slug-upstream.ts index 4cbf567f238..4184817e685 100644 --- a/src/main/github/client/fetch/repo-slug-upstream.ts +++ b/src/main/github/client/fetch/repo-slug-upstream.ts @@ -1,4 +1,12 @@ -import { ghExecFileAsync, acquire, release, type OwnerRepo } from '../../gh-utils' +import { + ghExecFileAsync, + acquire, + release, + getRemoteUrlForRepo, + githubRepoContext, + parseGitHubRemoteIdentity, + type OwnerRepo +} from '../../gh-utils' import { getHostedReviewLocalGitOptions, type HostedReviewExecutionOptions @@ -10,6 +18,17 @@ import { resolveGitHubRepoExecution, type GitHubApiRepository } from '../../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 { hostedReviewLocalGitOptionArgs, sameOwnerRepo } from './../github-exec-scope' export async function getRepoSlug( repoPath: string, @@ -23,55 +42,122 @@ export async function getRepoSlug( ) } -/** Best-effort fork parent for indicators/avatar selection; failures return null. */ +export type RepoUpstreamProbe = { + // Undefined is unavailable evidence, never a durable non-fork verdict. + upstream: OwnerRepo | null | undefined + origin: GitHubApiRepository | null +} + +export async function probeRepoUpstream( + repoPath: string, + connectionId?: string | null, + options: HostedReviewExecutionOptions = {}, + resolveParent = true +): Promise { + return withSharedRemoteUrlReads(async () => { + let origin: GitHubApiRepository | null = null + try { + const localGitOptions = hostedReviewLocalGitOptionArgs(options)[0] ?? {} + const context = githubRepoContext(repoPath, connectionId, localGitOptions) + let url: string | null + try { + url = await getRemoteUrlForRepo(context, 'origin') + } catch (error) { + if (isStableMissingGitRemoteError(error)) { + return { upstream: null, origin } + } + throw error + } + // An unserved remote host is not evidence of a missing origin. + if (url === null) { + return { upstream: undefined, origin } + } + const parsed = parseGitHubRemoteIdentity(url) + if (!parsed) { + return { upstream: null, origin } + } + let host = parsed.host + let hostResolved = true + const alias = gitHubSshConfigHostAlias(url) + if (alias) { + const resolved = await resolveSshConfigHostname(alias, context) + if (resolved.resolved && resolved.hostname) { + host = effectiveGitHubRemoteHost(host, resolved.hostname) + } else { + hostResolved = false + } + } + const forgeHost = normalizeForgeWebHost(foldWwwHostAlias(host)) + if (hostResolved && (forgeHost === 'gitlab.com' || forgeHost === 'bitbucket.org')) { + return { upstream: null, origin } + } + const execution = await resolveGitHubRepoExecution( + repoPath, + undefined, + connectionId, + localGitOptions + ) + origin = execution.ownerRepo + // Missing auth for an arbitrary custom host does not prove it is another forge. + if (!origin || !resolveParent) { + return { upstream: undefined, origin } + } + const upstream = await getGitHubApiRepositoryForRemote( + repoPath, + 'upstream', + connectionId, + localGitOptions + ) + if (upstream && !sameOwnerRepo(upstream, origin)) { + return { upstream, origin } + } + const controller = new AbortController() + const timer = setTimeout(() => controller.abort(), 10_000) + let acquired = false + try { + await acquire(controller.signal) + acquired = true + const { stdout } = await ghExecFileAsync( + ['repo', 'view', githubRepositorySlugArg(origin), '--json', 'isFork,parent'], + { ...execution.ghOptions, timeout: 10_000, signal: controller.signal } + ) + const data = JSON.parse(stdout) as { + isFork?: boolean + parent?: { name?: string; owner?: { login?: string } } | null + } + if (data.isFork === false) { + return { upstream: null, origin } + } + const owner = data.parent?.owner?.login + const repo = data.parent?.name + return { + upstream: + data.isFork === true && + typeof owner === 'string' && + owner.trim() && + typeof repo === 'string' && + repo.trim() + ? { owner, repo, ...(origin.host ? { host: origin.host } : {}) } + : undefined, + origin + } + } finally { + clearTimeout(timer) + if (acquired) { + release() + } + } + } catch { + return { upstream: undefined, origin } + } + }) +} + +/** Compatibility callers receive null when optional metadata is unavailable. */ export async function getRepoUpstream( repoPath: string, connectionId?: string | null, options: HostedReviewExecutionOptions = {} ): Promise { - const localGitArgs = hostedReviewLocalGitOptionArgs(options) - const localGitOptions = localGitArgs[0] ?? {} - const { ownerRepo: origin, ghOptions } = await resolveGitHubRepoExecution( - repoPath, - undefined, - connectionId, - localGitOptions - ) - if (!origin) { - return null - } - const upstreamRemote = await getGitHubApiRepositoryForRemote( - repoPath, - 'upstream', - connectionId, - localGitOptions - ) - if (upstreamRemote && !sameOwnerRepo(upstreamRemote, origin)) { - return upstreamRemote - } - await acquire() - try { - // Positional slugs bypass --repo qualification, so include the Enterprise host directly. - const { stdout } = await ghExecFileAsync( - ['repo', 'view', githubRepositorySlugArg(origin), '--json', 'isFork,parent'], - // Do not let optional metadata stall repository creation. - { - ...ghOptions, - timeout: 10_000 - } - ) - const data = JSON.parse(stdout) as { - isFork?: boolean - parent?: { name?: string; owner?: { login?: string } } | null - } - const owner = data.parent?.owner?.login - const repo = data.parent?.name - return data.isFork && owner && repo - ? { owner, repo, ...(origin.host ? { host: origin.host } : {}) } - : null - } catch { - return null - } finally { - release() - } + return (await probeRepoUpstream(repoPath, connectionId, options)).upstream ?? null } diff --git a/src/main/github/github-enterprise-repository.test.ts b/src/main/github/github-enterprise-repository.test.ts index 025609e3880..6a97404c2b7 100644 --- a/src/main/github/github-enterprise-repository.test.ts +++ b/src/main/github/github-enterprise-repository.test.ts @@ -33,6 +33,8 @@ import { isGitHubHostAuthenticated } from './github-enterprise-repository' import { _resetSshHostnameResolutionCache } from './github-ssh-host-alias-resolution' +import { getRepoUpstream, probeRepoUpstream } from './client/fetch/repo-slug-upstream' +import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository' function mockOriginRemote(url: string): void { gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { @@ -65,6 +67,25 @@ describe('getEnterpriseGitHubRepoSlug', () => { resolveWithSshGMock.mockResolvedValue(null) _resetGitHubHostAuthCache() _resetSshHostnameResolutionCache() + _resetOriginGitHubApiRepositoryCache() + }) + + it.each([ + ['https://bitbucket.org/team/orca.git', 'bitbucket.org'], + ['ssh://git@altssh.gitlab.com:443/team/orca.git', 'altssh.gitlab.com'], + ['https://codeberg.org/team/orca.git', 'codeberg.org'] + ])('does not promote a foreign public remote from gh inventory: %s', async (url, host) => { + mockOriginRemote(url) + mockHostAuthenticated(host) + await expect(getEnterpriseGitHubRepoSlug('/repo')).resolves.toBeFalsy() + await expect(isGitHubHostAuthenticated(host, '/repo')).resolves.toBe(false) + }) + + it('uses the effective SSH hostname before admitting an Enterprise identity', async () => { + mockOriginRemote('git@work-forge:team/orca.git') + resolveWithSshGMock.mockResolvedValue({ hostname: 'bitbucket.org' }) + mockHostAuthenticated('bitbucket.org') + await expect(getEnterpriseGitHubRepoSlug('/repo')).resolves.toBeNull() }) it.each([ @@ -93,6 +114,29 @@ describe('getEnterpriseGitHubRepoSlug', () => { host: 'ghe.acme.com:8443' }) }) + + it.each([true, false])( + 'keeps the literal Enterprise host fallback when SSH expansion fails (authenticated=%s)', + async (authenticated) => { + mockOriginRemote('git@ghe.corp.example:org/app.git') + ghExecFileAsyncMock.mockImplementation(async (args: string[]) => ({ + stdout: + args[0] === 'auth' + ? authenticated + ? 'ghe.corp.example\n ✓ Logged in to ghe.corp.example account kelora (keyring)' + : '' + : JSON.stringify({ isFork: true, parent: { owner: { login: 'parent' }, name: 'app' } }), + stderr: '' + })) + const expected = { owner: 'parent', repo: 'app', host: 'ghe.corp.example' } + const result = await probeRepoUpstream('/repo') + expect(result.upstream).toEqual(authenticated ? expected : undefined) + await expect(getRepoUpstream('/repo')).resolves.toEqual(authenticated ? expected : null) + expect(ghExecFileAsyncMock.mock.calls.filter(([args]) => args[0] === 'repo')).toHaveLength( + authenticated ? 2 : 0 + ) + } + ) }) describe('isGitHubHostAuthenticated', () => { diff --git a/src/main/github/github-enterprise-repository.ts b/src/main/github/github-enterprise-repository.ts index a0d590a6fb7..89a50c28ef2 100644 --- a/src/main/github/github-enterprise-repository.ts +++ b/src/main/github/github-enterprise-repository.ts @@ -22,6 +22,7 @@ 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 } @@ -131,6 +132,10 @@ async function resolveAuthenticatedGitHubHost( connectionId?: string | null, localGitOptions: LocalGitExecOptions = {} ): Promise { + const owner = getPublicForgeProviderForHost(host) + if (owner && owner !== 'github') { + return null + } const normalizedHost = normalizeGitHubHost(host)?.authority ?? host.trim().toLowerCase() const execOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)) const cacheKey = `${runtimeCacheKey(repoPath, connectionId, localGitOptions.wslDistro)}\0${normalizedHost}\0${githubReadExecutionScope(execOptions)}` diff --git a/src/main/github/github-repository-identity.fork-owner-repo.test.ts b/src/main/github/github-repository-identity.fork-owner-repo.test.ts index c697801eb0a..5e194798172 100644 --- a/src/main/github/github-repository-identity.fork-owner-repo.test.ts +++ b/src/main/github/github-repository-identity.fork-owner-repo.test.ts @@ -1,6 +1,6 @@ import type * as GitExecFileModule from '../git/command-runner/git-exec-file' import type * as GhExecFileModule from '../git/command-runner/gh-exec-file' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' // Fork PR reads prefer upstream while origin-only probes retain the checkout identity. @@ -29,7 +29,11 @@ vi.mock('./local-git-config-signature', () => ({ import { _resetRemoteNameListingCache } from '../git/remotes/remote-name-listing' import { getOwnerRepoForRemote, _resetOwnerRepoCache } from './github-repository-identity' import { getOwnerRepo } from './github-owner-repo-selection' -import { getRepoUpstream } from './client/fetch/repo-slug-upstream' +import { getRepoUpstream, probeRepoUpstream } from './client/fetch/repo-slug-upstream' + +import { acquire, release } from './gh-utils' + +afterEach(() => vi.useRealTimers()) const FORK_PATH = '/tmp/fork-checkout' const NON_FORK_PATH = '/tmp/plain-checkout' @@ -43,6 +47,8 @@ const REMOTE_URLS_BY_REPO: Record> = { [NON_FORK_PATH]: { origin: 'https://github.com/stablyai/orca.git' }, + '/tmp/gitlab': { origin: 'https://gitlab.com/group/widget.git' }, + '/tmp/custom': { origin: 'https://code.example.com/group/widget.git' }, [SSH_FORK_PATH]: { origin: 'git@github.com:fsdwen/orca.git', upstream: 'git@github.com:stablyai/orca.git' @@ -117,3 +123,59 @@ describe('issue #7331: fork PR owner/repo resolution', () => { expect(ghExecFileAsyncMock).not.toHaveBeenCalled() }) }) + +describe('optional parent evidence', () => { + it.each([ + ['{"isFork":false}', null], + [ + '{"isFork":true,"parent":{"owner":{"login":"acme"},"name":"widget"}}', + { owner: 'acme', repo: 'widget', host: 'github.com' } + ], + ['{"isFork":true,"parent":null}', undefined], + ['{}', undefined], + ['invalid', undefined] + ])('persists only successful fork evidence from %s', async (stdout, expected) => { + ghExecFileAsyncMock.mockResolvedValue({ stdout }) + expect((await probeRepoUpstream(NON_FORK_PATH)).upstream).toEqual(expected) + }) + + it('bounds global admission and leaves origin avatar evidence usable on failure', async () => { + vi.useFakeTimers() + for (let slot = 0; slot < 4; slot++) { + await acquire() + } + try { + const pending = probeRepoUpstream(NON_FORK_PATH) + await vi.advanceTimersByTimeAsync(10_000) + expect(await pending).toEqual({ + upstream: undefined, + origin: { owner: 'stablyai', repo: 'orca', host: 'github.com' } + }) + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + let nextStarted = false + const next = acquire().then(() => { + nextStarted = true + release() + }) + await Promise.resolve() + expect(nextStarted).toBe(false) + release() + await next + for (let slot = 0; slot < 3; slot++) { + release() + } + } catch (error) { + for (let slot = 0; slot < 4; slot++) { + release() + } + throw error + } + }) +}) + +it('settles proven missing/other-forge origins but leaves unclassified custom hosts unknown', async () => { + expect(await probeRepoUpstream('/tmp/no-origin')).toEqual({ upstream: null, origin: null }) + expect(await probeRepoUpstream('/tmp/gitlab')).toEqual({ upstream: null, origin: null }) + ghExecFileAsyncMock.mockRejectedValue(new Error('auth unavailable')) + expect(await probeRepoUpstream('/tmp/custom')).toEqual({ upstream: undefined, origin: null }) +}) diff --git a/src/main/gitlab/gitlab-project-ref-resolution.ts b/src/main/gitlab/gitlab-project-ref-resolution.ts index 3e3b57a90df..90d69bf6052 100644 --- a/src/main/gitlab/gitlab-project-ref-resolution.ts +++ b/src/main/gitlab/gitlab-project-ref-resolution.ts @@ -1,7 +1,6 @@ import { glabExecFileAsync } from '../git/runner' import type { GitAdmissionTier } from '../git/command-runner/git-exec-options' import { addWslEnvKeys } from '../../shared/wsl-env' -import { normalizeForgeWebHost } from '../../shared/git/remotes/git-remote-host-alias' 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' @@ -19,7 +18,7 @@ import { DEFAULT_GITLAB_HOSTS, normalizeGitLabHost, parseGitLabProjectRef, - parseRemoteProjectRefCandidate, + parseGitLabProjectRefCandidate, type ProjectRef } from './project-ref-parser' @@ -154,19 +153,12 @@ async function resolveProjectRefForRemote( if (stdout === null) { return null } - // Stray glab host entries for GitHub/Bitbucket hosts must not claim their remotes (#40386). - // Match the real host only: `github:team/project` is an scp remote on an SSH alias named github. - const remoteCandidate = parseRemoteProjectRefCandidate(stdout) - const remoteHost = remoteCandidate && normalizeForgeWebHost(remoteCandidate.host) - if (remoteHost === 'github.com' || remoteHost === 'bitbucket.org') { - publish(null) - return null - } const result = parseGitLabProjectRef(stdout, knownHosts) if (result) { publish(result) return result } + const remoteCandidate = parseGitLabProjectRefCandidate(stdout) if ( remoteCandidate && (await isGlabConfiguredForRemoteHost( diff --git a/src/main/gitlab/project-ref-parser.test.ts b/src/main/gitlab/project-ref-parser.test.ts index 6550aa5e402..c83ef13fe26 100644 --- a/src/main/gitlab/project-ref-parser.test.ts +++ b/src/main/gitlab/project-ref-parser.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { parseGitLabProjectRef } from './project-ref-parser' +import { parseGitLabProjectRef, parseRemoteProjectRefCandidate } from './project-ref-parser' describe('gitlab project ref parsing', () => { it.each([ @@ -43,4 +43,31 @@ describe('gitlab project ref parsing', () => { parseGitLabProjectRef('http://gitea.example.com:3030/team/api.git', knownHosts) ).toBeNull() }) + + it('keeps public ownership authoritative without narrowing generic mirror parsing', () => { + for (const [remote, host] of [ + ['https://github.com:8443/team/project.git', 'github.com:8443'], + ['git@SSH.GITHUB.COM:team/project.git', 'ssh.github.com'], + ['git@acme.ghe.com:team/project.git', 'acme.ghe.com'], + ['git@ssh.bitbucket.org:team/project.git', 'ssh.bitbucket.org'], + ['https://dev.azure.com/acme/project/_git/repo', 'dev.azure.com'], + ['git@ssh.dev.azure.com:v3/acme/project/repo', 'ssh.dev.azure.com'], + ['https://acme.visualstudio.com/project/_git/repo', 'acme.visualstudio.com'], + ['https://codeberg.org/team/project.git', 'codeberg.org'] + ]) { + expect(parseGitLabProjectRef(remote, [host])).toBeNull() + } + expect(parseRemoteProjectRefCandidate('git@github.com:team/project.git')).toEqual({ + host: 'github.com', + path: 'team/project' + }) + expect( + parseGitLabProjectRef('https://git.bitbucket.acme.com/team/project.git', [ + 'git.bitbucket.acme.com' + ]) + ).toEqual({ + host: 'git.bitbucket.acme.com', + path: 'team/project' + }) + }) }) diff --git a/src/main/gitlab/project-ref-parser.ts b/src/main/gitlab/project-ref-parser.ts index 051fdf1d062..96f083a6783 100644 --- a/src/main/gitlab/project-ref-parser.ts +++ b/src/main/gitlab/project-ref-parser.ts @@ -1,5 +1,6 @@ import type { GitLabProjectRef } from '../../shared/gitlab-types' import { normalizeGitLabRemoteHost } from '../../shared/git/remotes/git-remote-host-alias' +import { getPublicForgeProviderForHost } from '../../shared/git/remotes/public-forge-host' export type ProjectRef = GitLabProjectRef @@ -47,19 +48,6 @@ function knownHostMatches(urlHost: string, knownHost: string): boolean { return false } -function makeProjectRef( - host: string, - path: string, - knownHosts: readonly string[] -): ProjectRef | null { - const normalizedHost = normalizeGitLabRemoteHost(host) - const normalizedKnownHosts = knownHosts.map(normalizeGitLabHost) - if (!normalizedKnownHosts.some((knownHost) => knownHostMatches(normalizedHost, knownHost))) { - return null - } - return makeProjectRefForTrustedHost(normalizedHost, path) -} - export function parseRemoteProjectRefCandidate(remoteUrl: string): ProjectRef | null { const trimmed = remoteUrl.trim() if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) { @@ -80,25 +68,24 @@ export function parseRemoteProjectRefCandidate(remoteUrl: string): ProjectRef | } } +export function parseGitLabProjectRefCandidate(remoteUrl: string): ProjectRef | null { + const candidate = parseRemoteProjectRefCandidate(remoteUrl) + if (!candidate) { + return null + } + const owner = getPublicForgeProviderForHost(candidate.host) + return owner && owner !== 'gitlab' ? null : candidate +} + export function parseGitLabProjectRef( remoteUrl: string, knownHosts: readonly string[] = DEFAULT_GITLAB_HOSTS ): ProjectRef | null { - const trimmed = remoteUrl.trim() - if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) { - const scpLike = trimmed.match(/^(?:[^@/:]+@)?([^:\s/]+):([^\s]+?)(?:\.git)?$/) - if (scpLike) { - return makeProjectRef(scpLike[1], scpLike[2], knownHosts) - } - } - - try { - const url = new URL(trimmed) - if (!['http:', 'https:', 'ssh:', 'git:', 'git+ssh:'].includes(url.protocol.toLowerCase())) { - return null - } - return makeProjectRef(hostIdentityFromUrl(url), url.pathname, knownHosts) - } catch { + const candidate = parseGitLabProjectRefCandidate(remoteUrl) + if (!candidate) { return null } + return knownHosts.some((host) => knownHostMatches(candidate.host, normalizeGitLabHost(host))) + ? candidate + : null } diff --git a/src/main/gitlab/task-project-eligibility.test.ts b/src/main/gitlab/task-project-eligibility.test.ts index 894a356e3d7..1844b499abb 100644 --- a/src/main/gitlab/task-project-eligibility.test.ts +++ b/src/main/gitlab/task-project-eligibility.test.ts @@ -25,6 +25,8 @@ vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ })) import { listMergeRequests } from './merge-request-list' +import { isTaskRepositoryIneligible } from '../git/task-repository-eligibility' +import { rememberGlabKnownHosts } from './gitlab-known-host-probe' import { listIssues } from './issues' import { _resetProjectRefCache, _resetKnownHostsCache } from './gitlab-project-ref-resolution' import { _resetRemoteNameListingCache } from '../git/remotes/remote-name-listing' @@ -132,4 +134,9 @@ describe('GitLab task project admission', () => { expect(result.items).toEqual([]) expect(glab.mock.calls.filter(([args]) => args[0] !== 'auth')).toEqual([]) }) + + it('does not exclude GitHub tasks because glab remembers github.com', async () => { + rememberGlabKnownHosts(['github.com']) + await expect(isTaskRepositoryIneligible('/github', 'github')).resolves.toBe(false) + }) }) diff --git a/src/main/ipc/browser/desktop-browser-bridge-wiring.ts b/src/main/ipc/browser/desktop-browser-bridge-wiring.ts index e6f533b851a..cd40d4ad535 100644 --- a/src/main/ipc/browser/desktop-browser-bridge-wiring.ts +++ b/src/main/ipc/browser/desktop-browser-bridge-wiring.ts @@ -5,7 +5,9 @@ import { DESKTOP_BROWSER_BRIDGE_CANCEL_CAPABILITY, DESKTOP_BROWSER_BRIDGE_EXPECT_URL_CAPABILITY, DESKTOP_BROWSER_BRIDGE_RUNTIME_CAPABILITY, - isDesktopBrowserBridgeMethod + DESKTOP_BROWSER_BRIDGE_TAB_ANNOTATIONS_CAPABILITY, + isDesktopBrowserBridgeMethod, + isHostReachableDocument } from '../../../shared/desktop-browser-bridge-protocol' import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../shared/electron-remote-runtime-client-capabilities' import '../../../shared/remote-runtime/requests/remote-runtime-request-socket' @@ -22,10 +24,7 @@ import { DesktopBrowserBridgeManager, type DesktopBrowserBridgeCandidate } from '../../browser/desktop-browser-bridge/desktop-browser-bridge-manager' -import { - executeDesktopBrowserBridgeRequest, - isHostReachableDocument -} from '../../browser/desktop-browser-bridge/desktop-browser-bridge-executor' +import { executeDesktopBrowserBridgeRequest } from '../../browser/desktop-browser-bridge/desktop-browser-bridge-executor' import { rendererResolveRemoteCliWorkspace } from '../../browser/desktop-browser-bridge/desktop-browser-bridge-renderer-scope' import type { OrcaRuntimeService } from '../../runtime/orca-runtime' import { RpcDispatcher } from '../../runtime/rpc/dispatcher' @@ -153,7 +152,8 @@ export function installDesktopBrowserBridge(options: { ...ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES, DESKTOP_BROWSER_BRIDGE_RUNTIME_CAPABILITY, DESKTOP_BROWSER_BRIDGE_CANCEL_CAPABILITY, - DESKTOP_BROWSER_BRIDGE_EXPECT_URL_CAPABILITY + DESKTOP_BROWSER_BRIDGE_EXPECT_URL_CAPABILITY, + DESKTOP_BROWSER_BRIDGE_TAB_ANNOTATIONS_CAPABILITY ] } ) diff --git a/src/main/ipc/repos-nested-import.test.ts b/src/main/ipc/repos-nested-import.test.ts index f70d1a9bae3..a3cfc198564 100644 --- a/src/main/ipc/repos-nested-import.test.ts +++ b/src/main/ipc/repos-nested-import.test.ts @@ -70,7 +70,17 @@ describe('projectGroups IPC validation', () => { mockWindow.webContents.send.mockReset() resetProjectGroupMocks(reposMocks, { isGitRepo, getGitRepoRoot }) - registerRepoHandlers(mockWindow as never, mockStore as never, {} as never) + registerRepoHandlers( + mockWindow as never, + mockStore as never, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: These IPC cases use only the metadata owner's enqueue method; other runtime handlers are not invoked. + { + repositoryForkBackfill: { + enqueue: vi.fn().mockResolvedValue(undefined), + resolve: vi.fn().mockResolvedValue(true) + } + } as never + ) }) const group = { diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts index 68ae1b3aed9..24448a20635 100644 --- a/src/main/ipc/repos.ts +++ b/src/main/ipc/repos.ts @@ -66,14 +66,22 @@ export function registerRepoHandlers( ipcMain.removeHandler('sparsePresets:remove') registerRepoCatalogHandlers(mainWindow, store, runtime) - registerProjectHostSetupHandlers(mainWindow, store) - registerRepoCreationHandlers(mainWindow, store) + const metadata = { + enqueueRepositoryMetadata: ( + repos: Parameters[0] + ) => void runtime.repositoryForkBackfill.enqueue(repos), + resolveRepositoryMetadata: ( + repo: Parameters[0] + ) => runtime.repositoryForkBackfill.resolve(repo) + } + registerProjectHostSetupHandlers(mainWindow, store, metadata) + registerRepoCreationHandlers(mainWindow, store, metadata.enqueueRepositoryMetadata) registerProjectGroupHandlers(mainWindow, store) registerFolderWorkspaceHandlers(mainWindow, store, runtime) - registerNestedRepoImportHandler(mainWindow, store) + registerNestedRepoImportHandler(mainWindow, store, metadata.enqueueRepositoryMetadata) registerRepoUpdateHandler(mainWindow, store) registerSparsePresetHandlers(mainWindow, store) registerRepoFolderPickerHandlers(mainWindow) - registerRepoCloneHandlers(mainWindow, store) + registerRepoCloneHandlers(mainWindow, store, metadata.enqueueRepositoryMetadata) registerBaseRefQueryHandlers(store) } diff --git a/src/main/ipc/repos/local-repo-registration.test.ts b/src/main/ipc/repos/local-repo-registration.test.ts index 8cae231ea9d..53b854a0ab4 100644 --- a/src/main/ipc/repos/local-repo-registration.test.ts +++ b/src/main/ipc/repos/local-repo-registration.test.ts @@ -7,7 +7,7 @@ import type { Store } from '../../persistence/loading-store/store' import { addLocalRepoFromPath } from './local-repo-registration' vi.mock('../../repository-icons/repo-icon-autodetect', () => ({ - detectRepoIconAndUpstream: vi.fn().mockResolvedValue({}) + detectRepoLocalMetadata: vi.fn().mockResolvedValue({}) })) vi.mock('../../workspaces/creation/worktree-root-preparation', () => ({ prepareLocalWorktreeRootForRepo: vi.fn().mockResolvedValue(undefined) diff --git a/src/main/ipc/repos/local-repo-registration.ts b/src/main/ipc/repos/local-repo-registration.ts index 5f447575fd1..53f4c136704 100644 --- a/src/main/ipc/repos/local-repo-registration.ts +++ b/src/main/ipc/repos/local-repo-registration.ts @@ -10,7 +10,7 @@ import { } from '../../git/repo' import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' import { findProjectAtSameRealPath } from '../../workspaces/catalog/project-realpath-identity' -import { detectRepoIconAndUpstream } from '../../repository-icons/repo-icon-autodetect' +import { detectRepoLocalMetadata } from '../../repository-icons/repo-icon-autodetect' import { prepareLocalWorktreeRootForRepo } from '../../workspaces/creation/worktree-root-preparation' import { describeWslUncAccessDenied } from '../../wsl/filesystem/wsl-unc-access-denied' import { createLocalProjectRecord } from '../../workspaces/catalog/local-project-record' @@ -86,7 +86,7 @@ export async function addLocalRepoFromPath( } } - const detected = await detectRepoIconAndUpstream({ + const detected = await detectRepoLocalMetadata({ repoPath: resolvedPath, kind: repoKind, executionHostId: LOCAL_EXECUTION_HOST_ID diff --git a/src/main/ipc/repos/nested-repo-import-handler.ts b/src/main/ipc/repos/nested-repo-import-handler.ts index 84dc522b3c2..bc4768f64c0 100644 --- a/src/main/ipc/repos/nested-repo-import-handler.ts +++ b/src/main/ipc/repos/nested-repo-import-handler.ts @@ -4,6 +4,7 @@ import { randomUUID } from 'node:crypto' import { realpath } from 'node:fs/promises' import type { Store } from '../../persistence/loading-store/store' import type { Repo } from '../../../shared/repo-types' +import type { RepositoryMetadataOwner } from '../../workspaces/catalog/imported-folder-project-link' import type { ProjectGroupImportResult } from '../../../shared/project-group-types' import { DEFAULT_REPO_BADGE_COLOR } from '../../../shared/constants' import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' @@ -15,7 +16,7 @@ import { } from '../../project-groups/nested-repo-import' import { createNestedRepoImportTargetResolver } from '../../project-groups/nested-repo-import-target' import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' -import { detectRepoIconAndUpstream } from '../../repository-icons/repo-icon-autodetect' +import { detectRepoLocalMetadata } from '../../repository-icons/repo-icon-autodetect' import { prepareLocalWorktreeRootForRepo } from '../../workspaces/creation/worktree-root-preparation' import { invalidateAuthorizedRootsCache } from '../worktrees/removal/registered-worktree-roots-cache' import { emitRepoAdded } from './repo-added-telemetry' @@ -28,7 +29,11 @@ function sanitizeNestedRepoImportError(context: string, error: unknown): string return 'Repository could not be imported' } -export function registerNestedRepoImportHandler(mainWindow: BrowserWindow, store: Store): void { +export function registerNestedRepoImportHandler( + mainWindow: BrowserWindow, + store: Store, + enqueueMetadata: RepositoryMetadataOwner['enqueueRepositoryMetadata'] +): void { ipcMain.handle( 'projectGroups:importNested', async (_event, rawArgs: unknown): Promise => { @@ -65,6 +70,7 @@ export function registerNestedRepoImportHandler(mainWindow: BrowserWindow, store const importedProjectIdsByRepoPath = new Map() const importTargetResolver = createNestedRepoImportTargetResolver() + const acceptedRepos: Repo[] = [] for (const [projectGroupOrder, repoPath] of selection.selectedPaths.entries()) { try { // This process cannot validate SSH paths with local Git. @@ -117,7 +123,7 @@ export function registerNestedRepoImportHandler(mainWindow: BrowserWindow, store results.push({ path: repoPath, projectId: existing.id, status: 'already-known' }) continue } - const detected = await detectRepoIconAndUpstream({ + const detected = await detectRepoLocalMetadata({ repoPath: importRepoPath, kind: 'git', executionHostId: LOCAL_EXECUTION_HOST_ID @@ -140,6 +146,7 @@ export function registerNestedRepoImportHandler(mainWindow: BrowserWindow, store : {}) } store.addRepo(repo) + acceptedRepos.push(repo) await prepareLocalWorktreeRootForRepo(store, repo) importedProjectIdsByRepoPath.set(normalizedImportRepoPath, repo.id) results.push({ path: repoPath, projectId: repo.id, status: 'imported' }) @@ -153,6 +160,7 @@ export function registerNestedRepoImportHandler(mainWindow: BrowserWindow, store } } + enqueueMetadata(acceptedRepos) const importedCount = results.filter((entry) => entry.status === 'imported').length const alreadyKnownCount = results.filter((entry) => entry.status === 'already-known').length const failedCount = results.filter((entry) => entry.status === 'failed').length diff --git a/src/main/ipc/repos/project-host-setup-handlers.ts b/src/main/ipc/repos/project-host-setup-handlers.ts index 61f412d26cc..7326003eb2e 100644 --- a/src/main/ipc/repos/project-host-setup-handlers.ts +++ b/src/main/ipc/repos/project-host-setup-handlers.ts @@ -13,7 +13,10 @@ import type { ProjectHostSetupUpdateResult } from '../../../shared/project-types' import { getProjectHostSetupForRepo } from '../../../shared/project-host-setup-lookup' -import { resolveImportedFolderProjectLink } from '../../../shared/imported-folder-project-identity' +import { + linkImportedFolderToProject, + type RepositoryMetadataOwner +} from '../../workspaces/catalog/imported-folder-project-link' import { readCurrentGitRemoteIdentity } from '../../workspaces/catalog/repo-git-remote-identity' import { getRepoExecutionHostId, parseExecutionHostId } from '../../../shared/execution-host' import { prepareLocalWorktreeRootForRepo } from '../../workspaces/creation/worktree-root-preparation' @@ -45,48 +48,11 @@ function buildProjectHostSetupResult(store: Store, repo: Repo): ProjectHostSetup return { project, setup, repo } } -function alignRepoWithRequestedProject( +export function registerProjectHostSetupHandlers( + mainWindow: BrowserWindow, store: Store, - repo: Repo, - folderRemote: Pick, - projectId: string, - setupMethod: ProjectHostSetupExistingFolderArgs['setupMethod'] = 'imported-existing-folder', - requestedProviderIdentity?: ProjectHostSetupExistingFolderArgs['projectProviderIdentity'] -): ProjectHostSetupResult { - assertWslMoveHostSetupWritable(store, { - projectId, - hostId: getRepoExecutionHostId(repo), - repoId: repo.id - }) - let setup = getProjectHostSetupForRepo(store.getProjectHostSetups(), repo) - if (setup.projectId !== projectId) { - const project = store.getProjects().find((entry) => entry.id === projectId) - // Project identity must travel with the request when it exists only on the source host. - const updated = store.updateRepo( - repo, - resolveImportedFolderProjectLink( - { ...repo, ...folderRemote }, - projectId, - project?.providerIdentity ?? requestedProviderIdentity - ) - ) - if (!updated) { - throw new Error(`Project setup repo disappeared before it could be linked: ${repo.id}`) - } - repo = updated - setup = getProjectHostSetupForRepo(store.getProjectHostSetups(), repo) - } - const updated = store.updateRepo(repo, { projectHostSetupMethod: setupMethod }) - if (!updated) { - throw new Error( - `Project setup repo disappeared before setup metadata could be linked: ${repo.id}` - ) - } - repo = updated - return buildProjectHostSetupResult(store, repo) -} - -export function registerProjectHostSetupHandlers(mainWindow: BrowserWindow, store: Store): void { + metadata: RepositoryMetadataOwner +): void { ipcMain.handle( 'projectHostSetups:create', (_event, rawArgs: ProjectHostSetupCreateArgs): ProjectHostSetupCreateResult => { @@ -191,20 +157,21 @@ export function registerProjectHostSetupHandlers(mainWindow: BrowserWindow, stor : result.repo let aligned: ProjectHostSetupResult try { - aligned = alignRepoWithRequestedProject( - store, + const repo = await linkImportedFolderToProject( + () => store, result.repo, folderRemote, - args.projectId, - args.setupMethod, - args.projectProviderIdentity + { ...args, hostId: getRepoExecutionHostId(result.repo) }, + metadata ) + aligned = buildProjectHostSetupResult(store, repo) } catch (err) { // Failed linking must not leave a newly registered repo or authorization root. if (!result.alreadyExisted) { store.removeProjectForHost(result.repo) invalidateAuthorizedRootsCache() } + notifyReposChanged(mainWindow) throw err } invalidateAuthorizedRootsCache() diff --git a/src/main/ipc/repos/project-host-setup-wsl-move-fence.test.ts b/src/main/ipc/repos/project-host-setup-wsl-move-fence.test.ts index a450dcab9d3..98cdb340348 100644 --- a/src/main/ipc/repos/project-host-setup-wsl-move-fence.test.ts +++ b/src/main/ipc/repos/project-host-setup-wsl-move-fence.test.ts @@ -83,7 +83,10 @@ describe('project host setups under a WSL move', () => { store.addRepo(repo('repo-1')) store.addRepo(repo('repo-2')) seedWslMoveCutover(testState.dir, cutover('move-1', 'source-fenced')) - registerProjectHostSetupHandlers(new BrowserWindow(), store) + registerProjectHostSetupHandlers(new BrowserWindow(), store, { + enqueueRepositoryMetadata: vi.fn(), + resolveRepositoryMetadata: vi.fn().mockResolvedValue(true) + }) const moving = setupFor('repo-1') await expect( @@ -107,7 +110,10 @@ describe('project host setups under a WSL move', () => { it("keeps a setup's own repo frozen once the WSL host owns it", async () => { store.addRepo(repo('repo-1')) seedWslMoveCutover(testState.dir, cutover('move-1', 'destination-committed')) - registerProjectHostSetupHandlers(new BrowserWindow(), store) + registerProjectHostSetupHandlers(new BrowserWindow(), store, { + enqueueRepositoryMetadata: vi.fn(), + resolveRepositoryMetadata: vi.fn().mockResolvedValue(true) + }) const owned = setupFor('repo-1') await expect( @@ -129,6 +135,8 @@ describe('project host setups under a WSL move', () => { invalidateResolvedWorktrees: vi.fn(), invalidateWorktreeScan: vi.fn(), notifyReposChanged: vi.fn(), + enqueueRepositoryMetadata: vi.fn(), + resolveRepositoryMetadata: vi.fn().mockResolvedValue(true), countLiveTerminalsForRepo: () => 0 }) const setupId = setupFor('repo-1').id diff --git a/src/main/ipc/repos/repo-clone-lifecycle.ts b/src/main/ipc/repos/repo-clone-lifecycle.ts index bd68750b60e..422d3833f68 100644 --- a/src/main/ipc/repos/repo-clone-lifecycle.ts +++ b/src/main/ipc/repos/repo-clone-lifecycle.ts @@ -22,14 +22,16 @@ import { getSavedProjectPathKeys } from '../../git/repo-clone-path' import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' -import { detectRepoIconAndUpstream } from '../../repository-icons/repo-icon-autodetect' +import { detectRepoLocalMetadata } from '../../repository-icons/repo-icon-autodetect' import { prepareLocalWorktreeRootForRepo } from '../../workspaces/creation/worktree-root-preparation' import { invalidateAuthorizedRootsCache } from '../worktrees/removal/registered-worktree-roots-cache' import { emitRepoAdded } from './repo-added-telemetry' import { notifyReposChanged } from './repos-changed-notification' import { runWithClonePathLock } from './clone-path-lock' +import { emitCloneProgressFromText } from './repo-clone-progress' import { resolveClonedFolderConversion } from '../../workspaces/catalog/folder-repo-git-conversion' import { findExtraFolderWorkspaceIds } from '../../workspaces/catalog/folder-workspace-meta-presence' +import type { RepositoryMetadataOwner } from '../../workspaces/catalog/imported-folder-project-link' type ActiveCloneMetadata = { path: string @@ -49,18 +51,6 @@ let nextCloneGeneration = 1 const latestCloneGenerationByPath = new Map() const pendingAbortCleanupByPath = new Map>() -function emitCloneProgressFromText(mainWindow: BrowserWindow, text: string): void { - for (const line of text.split(/[\r\n]+/)) { - const match = line.match(/^([\w\s]+):\s+(\d+)%/) - if (match && !mainWindow.isDestroyed()) { - mainWindow.webContents.send('repos:clone-progress', { - phase: match[1].trim(), - percent: Number.parseInt(match[2], 10) - }) - } - } -} - async function cleanupOwnedCloneTarget(metadata: ActiveCloneMetadata): Promise { if (!metadata.claimedTarget.canCleanup || !metadata.claimedTarget.ownedDirectoryIdentity) { return @@ -102,7 +92,11 @@ function settleCloneAbortCleanup(metadata: ActiveCloneMetadata): void { metadata.resolvePendingAbortCleanup = null } -export function registerRepoCloneHandlers(mainWindow: BrowserWindow, store: Store): void { +export function registerRepoCloneHandlers( + mainWindow: BrowserWindow, + store: Store, + enqueueMetadata: RepositoryMetadataOwner['enqueueRepositoryMetadata'] +): void { ipcMain.handle('repos:cloneAbort', async () => { for (const controller of pendingLocalCloneControllers) { controller.abort() @@ -136,7 +130,7 @@ export function registerRepoCloneHandlers(mainWindow: BrowserWindow, store: Stor const clonePathKey = getClonePathComparisonKey(clonePath) let savedPathKeys: string[] = [] const findSaved = (): Repo | undefined => findLocalSaved(savedPathKeys) - return runWithClonePathLock(clonePathKey, async () => { + const repo = await runWithClonePathLock(clonePathKey, async () => { await pendingAbortCleanupByPath.get(clonePathKey) // Read after the lock so lookup sees what a queued clone of this path registered. savedPathKeys = await getSavedProjectPathKeys(clonePath) @@ -299,7 +293,7 @@ export function registerRepoCloneHandlers(mainWindow: BrowserWindow, store: Stor // Register Git's checkout path so the clone stays its own selected checkout. const repoPath = (await inspectGitRepoForRegistrationAsync(clonePath)).rootPath - const detected = await detectRepoIconAndUpstream({ + const detected = await detectRepoLocalMetadata({ repoPath, kind: 'git', executionHostId: LOCAL_EXECUTION_HOST_ID @@ -329,5 +323,7 @@ export function registerRepoCloneHandlers(mainWindow: BrowserWindow, store: Stor } } }) + enqueueMetadata([repo]) + return repo }) } diff --git a/src/main/ipc/repos/repo-clone-progress.ts b/src/main/ipc/repos/repo-clone-progress.ts new file mode 100644 index 00000000000..cce16fbcd9c --- /dev/null +++ b/src/main/ipc/repos/repo-clone-progress.ts @@ -0,0 +1,13 @@ +import type { BrowserWindow } from 'electron' + +export function emitCloneProgressFromText(mainWindow: BrowserWindow, text: string): void { + for (const line of text.split(/[\r\n]+/)) { + const match = line.match(/^([\w\s]+):\s+(\d+)%/) + if (match && !mainWindow.isDestroyed()) { + mainWindow.webContents.send('repos:clone-progress', { + phase: match[1].trim(), + percent: Number.parseInt(match[2], 10) + }) + } + } +} diff --git a/src/main/ipc/repos/repo-creation-handlers.ts b/src/main/ipc/repos/repo-creation-handlers.ts index 25aed3525a0..d17a56ee3ba 100644 --- a/src/main/ipc/repos/repo-creation-handlers.ts +++ b/src/main/ipc/repos/repo-creation-handlers.ts @@ -6,6 +6,7 @@ import { homedir } from 'node:os' import { isAbsolute, join } from 'node:path' import type { Store } from '../../persistence/loading-store/store' import type { Repo } from '../../../shared/repo-types' +import type { RepositoryMetadataOwner } from '../../workspaces/catalog/imported-folder-project-link' import { DEFAULT_REPO_BADGE_COLOR, getDefaultWorkspaceDir } from '../../../shared/constants' import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' @@ -14,7 +15,7 @@ import { probeGitAvailability } from '../../git/git-availability' import { gitExecFileAsync } from '../../git/runner' import { inspectGitRepoForRegistrationAsync } from '../../git/repo' import { getClonePathComparisonKey, getSavedProjectPathKeys } from '../../git/repo-clone-path' -import { detectRepoIconAndUpstream } from '../../repository-icons/repo-icon-autodetect' +import { detectRepoLocalMetadata } from '../../repository-icons/repo-icon-autodetect' import { prepareLocalWorktreeRootForRepo } from '../../workspaces/creation/worktree-root-preparation' import { invalidateAuthorizedRootsCache } from '../worktrees/removal/registered-worktree-roots-cache' import { repoCreateFailure, type RepoCreateFailure } from '../../../shared/repo-create-failure-copy' @@ -51,7 +52,11 @@ function getDefaultCreateProjectParent(store: Store): string { return join(home, 'orca', 'projects') } -export function registerRepoCreationHandlers(mainWindow: BrowserWindow, store: Store): void { +export function registerRepoCreationHandlers( + mainWindow: BrowserWindow, + store: Store, + enqueueMetadata: RepositoryMetadataOwner['enqueueRepositoryMetadata'] +): void { ipcMain.handle('repos:isGitAvailable', () => probeLocalGitAvailability()) ipcMain.handle('repos:getDefaultCreateProjectParent', () => getDefaultCreateProjectParent(store)) @@ -70,6 +75,7 @@ export function registerRepoCreationHandlers(mainWindow: BrowserWindow, store: S } invalidateAuthorizedRootsCache() notifyReposChanged(mainWindow) + enqueueMetadata([result.repo]) emitRepoAdded('folder_picker', result.alreadyExisted, result.repo.kind === 'git') return { repo: result.repo } } @@ -222,7 +228,7 @@ export function registerRepoCreationHandlers(mainWindow: BrowserWindow, store: S repoKind === 'git' ? (await inspectGitRepoForRegistrationAsync(targetPath)).rootPath : targetPath - const detected = await detectRepoIconAndUpstream({ + const detected = await detectRepoLocalMetadata({ repoPath, kind: repoKind, executionHostId: LOCAL_EXECUTION_HOST_ID @@ -244,6 +250,7 @@ export function registerRepoCreationHandlers(mainWindow: BrowserWindow, store: S } store.addRepo(repo) + enqueueMetadata([repo]) await prepareLocalWorktreeRootForRepo(store, repo) invalidateAuthorizedRootsCache() notifyReposChanged(mainWindow) 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 b90609fc5ed..37122867666 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 @@ -62,7 +62,8 @@ export async function resolveAgentModelCatalogScope( // The list belongs to the account and the CLI a chat here would launch, not to this folder: // resolve the executable where the chat runs, but list from an empty Orca-owned folder so the // listing reads only account settings (a home folder can hold another account's settings as - // project settings) and every workspace sharing that invocation shares one listing. + // project settings) and every workspace sharing that invocation shares one listing. A command + // line that may name files in the chat's folder lists there instead (`catalogListingDirectory`). let listIn: string try { listIn = resolveHiddenProbeCwd() diff --git a/src/main/native-chat/agent-session-journal/input-order/journal-input-obligations.ts b/src/main/native-chat/agent-session-journal/input-order/journal-input-obligations.ts index 87ba94bcabf..e3964f7f6ef 100644 --- a/src/main/native-chat/agent-session-journal/input-order/journal-input-obligations.ts +++ b/src/main/native-chat/agent-session-journal/input-order/journal-input-obligations.ts @@ -265,6 +265,10 @@ export function journalInputPresentationMember( state: JournalReducerState, itemId: string ): boolean { + // Renders ask this of every row on each commit; parsing each key froze main in big chats (#40682). + if (state.inputs.rejections.size === 0) { + return true + } const identity = parseAgentJournalItemKey(itemId) return ( identity?.provider !== 'orca' || diff --git a/src/main/orca-profiles/profile-cloud-client.test.ts b/src/main/orca-profiles/profile-cloud-client.test.ts new file mode 100644 index 00000000000..bfd9ef8b54a --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-client.test.ts @@ -0,0 +1,36 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' +import { createOrcaCloudProfile, OrcaCloudRequestError } from './profile-cloud-client' +import type { OrcaCloudSession } from './profile-cloud-session-store' + +afterEach(() => { + vi.unstubAllGlobals() +}) + +describe('createOrcaCloudProfile', () => { + it('proves the sign-in with its refresh token alongside the access token', async () => { + const fetchImpl = vi.fn( + async () => new Response(null, { status: 403 }) + ) + vi.stubGlobal('fetch', fetchImpl) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the call reads only this endpoint. + const config = { + profileEndpoint: 'https://login.test/v1/desktop/auth/profile' + } as OrcaCloudAuthConfig + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the call reads only the two tokens. + const session = { accessToken: 'access-1', refreshToken: 'refresh-1' } as OrcaCloudSession + + await expect( + createOrcaCloudProfile(config, session, { orgId: 'org-1', name: 'Work' }) + ).rejects.toBeInstanceOf(OrcaCloudRequestError) + + const [url, init] = fetchImpl.mock.calls[0]! + expect(url).toBe('https://login.test/v1/desktop/auth/profile') + expect(new Headers(init?.headers).get('authorization')).toBe('Bearer access-1') + expect(JSON.parse(String(init?.body))).toEqual({ + orgId: 'org-1', + name: 'Work', + refreshToken: 'refresh-1' + }) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-client.ts b/src/main/orca-profiles/profile-cloud-client.ts index baa4cf1e471..a8835d167ce 100644 --- a/src/main/orca-profiles/profile-cloud-client.ts +++ b/src/main/orca-profiles/profile-cloud-client.ts @@ -157,8 +157,8 @@ function normalizeSessionResponse(value: unknown): OrcaCloudSessionExchangeRespo const CLOUD_REQUEST_TIMEOUT_MS = 30_000 -// A lost rotating-token response makes retries ambiguous; one longer attempt avoids replay. -const CLOUD_REFRESH_TIMEOUT_MS = 60_000 +// Two attempts plus the replay delay must settle inside the server's 60s rotation grace. +const CLOUD_REFRESH_TIMEOUT_MS = 20_000 type PostJsonOptions = { accessToken?: string @@ -170,6 +170,22 @@ export function isAmbiguousCloudRequestFailure(error: unknown): boolean { return !(error instanceof OrcaCloudRequestError) } +// Proxies, CDNs and gateways answer with HTML; only the auth server's JSON carries a verdict. +async function readCloudErrorCode(response: Response): Promise { + if (!response.headers.get('content-type')?.toLowerCase().includes('application/json')) { + await cancelUnreadResponseBody(response) + return undefined + } + try { + const body: unknown = await response.json() + return body && typeof body === 'object' && 'error' in body && typeof body.error === 'string' + ? body.error + : undefined + } catch { + return undefined + } +} + async function postJson(url: string, body: unknown, options?: PostJsonOptions): Promise { const response = await fetch(url, { method: 'POST', @@ -183,8 +199,7 @@ async function postJson(url: string, body: unknown, options?: PostJsonOptions signal: AbortSignal.timeout(options?.timeoutMs ?? CLOUD_REQUEST_TIMEOUT_MS) }) if (!response.ok) { - await cancelUnreadResponseBody(response) - throw new OrcaCloudRequestError(response.status) + throw new OrcaCloudRequestError(response.status, await readCloudErrorCode(response)) } return (await response.json()) as T } @@ -242,10 +257,8 @@ export async function createOrcaCloudProfile( return normalizeSessionResponse( await postJson( config.profileEndpoint, - { - orgId: args.orgId, - name: args.name - }, + // The refresh token proves the long-lived sign-in, not just a short-lived access token. + { orgId: args.orgId, name: args.name, refreshToken: session.refreshToken }, { accessToken: session.accessToken } ) ) diff --git a/src/main/orca-profiles/profile-cloud-refresh-replay-guard.ts b/src/main/orca-profiles/profile-cloud-refresh-replay-guard.ts index 5290fe347c8..0efc33c094a 100644 --- a/src/main/orca-profiles/profile-cloud-refresh-replay-guard.ts +++ b/src/main/orca-profiles/profile-cloud-refresh-replay-guard.ts @@ -1,7 +1,7 @@ // Lost refresh replies may have rotated the token; replay can revoke the entire token family. // Briefly block retry loops after ambiguous rotation to avoid replay storms. -export const AMBIGUOUS_REFRESH_REPLAY_DELAY_MS = 30_000 +export const AMBIGUOUS_REFRESH_REPLAY_DELAY_MS = 10_000 const AMBIGUOUS_REFRESH_ATTEMPTS_MAX_ENTRIES = 512 type AmbiguousRefreshAttempt = { diff --git a/src/main/orca-profiles/profile-cloud-session-refresh.test.ts b/src/main/orca-profiles/profile-cloud-session-refresh.test.ts new file mode 100644 index 00000000000..137b335b0da --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-session-refresh.test.ts @@ -0,0 +1,275 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' +import type { ActiveOrcaProfileState } from './profile-index-store' +import type { OrcaCloudSession } from './profile-cloud-session-store' +import type { OrcaProfileSummary } from '../../shared/orca-profiles' + +const store = vi.hoisted(() => { + const state: { session: OrcaCloudSession | null; signedOut: number } = { + session: null, + signedOut: 0 + } + return state +}) + +vi.mock('./profile-cloud-session-owner', () => ({ + readCloudSession: () => + store.session ? { status: 'found', session: store.session } : { status: 'missing' }, + takeCloudSessionTicket: () => 1, + commitCloudSessionRotation: ( + _profileId: string, + _userDataPath: string, + _ticket: number, + _previous: OrcaCloudSession, + next: OrcaCloudSession + ) => { + store.session = { + accessToken: next.accessToken, + refreshToken: next.refreshToken, + expiresAt: next.expiresAt, + capabilities: next.capabilities + } + return store.session + }, + signOutRevokedCloudSession: ( + _profileId: string, + _userDataPath: string, + failed: OrcaCloudSession + ) => { + if (store.session?.refreshToken !== failed.refreshToken) { + return false + } + store.session = null + store.signedOut += 1 + return true + } +})) + +import { OrcaCloudRequestError } from './profile-cloud-client' +import { + readFreshOrcaCloudSession, + runWithFreshOrcaCloudSession +} from './profile-cloud-session-refresh' + +const HOUR_MS = 3_600_000 +const SERVER_ROTATION_GRACE_MS = 60_000 +const HTML_403 = '

403 Forbidden

' +const HTML_502 = '

502 Bad Gateway

' + +const AUTH = 'https://auth.example.test' +const config: OrcaCloudAuthConfig = { + apiBaseUrl: AUTH, + authorizeEndpoint: `${AUTH}/authorize`, + sessionEndpoint: `${AUTH}/session`, + refreshEndpoint: `${AUTH}/refresh`, + capabilitiesEndpoint: `${AUTH}/capabilities`, + profileEndpoint: `${AUTH}/profile`, + orgEndpoint: `${AUTH}/org`, + logoutEndpoint: `${AUTH}/logout`, + relayTokenEndpoint: `${AUTH}/relay-token`, + connectorTokenEndpoint: `${AUTH}/connector-token`, + relayDirectorUrl: AUTH, + clientId: 'client-1', + scope: 'openid' +} + +let seq = 0 +let refreshCalls = 0 +let answerRefresh: (refreshToken: string) => Promise + +function reply(status: number, body: string, type = 'application/json'): Response { + return new Response(body, { status, headers: { 'content-type': type } }) +} + +function sessionReply(refreshToken: string): Response { + return reply( + 200, + JSON.stringify({ + accessToken: `access-${refreshToken}`, + refreshToken, + expiresAt: Date.now() + HOUR_MS, + cloud: { cloudProfileId: 'cloud-profile-1', userId: 'user-1', email: 'a@example.com' }, + capabilities: { flags: {}, refreshedAt: 1 } + }) + ) +} + +function signedIn(expired = true): ActiveOrcaProfileState { + seq += 1 + store.signedOut = 0 + store.session = { + accessToken: 'access-old', + refreshToken: `refresh-old-${seq}`, + expiresAt: expired ? Date.now() - 1 : Date.now() + HOUR_MS, + capabilities: { flags: {}, refreshedAt: 1 } + } + // A fresh profile id keeps the module's single-flight and replay-guard state per test. + const profile: OrcaProfileSummary = { + id: `profile-${seq}`, + name: 'Profile', + avatar: { kind: 'initials', initials: 'P', color: 'neutral' }, + kind: 'cloud-linked', + createdAt: 1, + updatedAt: 1, + lastOpenedAt: 1, + cloud: { + userId: 'user-1', + cloudProfileId: 'cloud-profile-1', + email: 'a@example.com', + linkedAt: 1 + } + } + return { + index: { schemaVersion: 1, activeProfileId: profile.id, profiles: [profile] }, + profile, + dataFile: '', + stateDatabaseFile: '', + profileDirectory: '' + } +} + +async function settle(promise: Promise): Promise { + const settled = promise.catch(() => 'threw') + await vi.advanceTimersByTimeAsync(5 * 60_000) + return settled +} + +beforeEach(() => { + // Response body streams schedule on real immediates; only the request clock is faked. + vi.useFakeTimers({ now: 1_000_000, toFake: ['setTimeout', 'clearTimeout', 'Date'] }) + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + // Route request timeouts through fake timers so the timeout chain runs on the test clock. + vi.spyOn(AbortSignal, 'timeout').mockImplementation((ms) => { + const controller = new AbortController() + setTimeout(() => controller.abort(new DOMException('timed out', 'TimeoutError')), ms) + return controller.signal + }) + refreshCalls = 0 + vi.stubGlobal('fetch', (_url: string, init: RequestInit) => { + refreshCalls += 1 + const body: { refreshToken?: unknown } = JSON.parse(String(init.body)) + const refreshToken = String(body.refreshToken) + return Promise.race([ + answerRefresh(refreshToken), + new Promise((_, reject) => + init.signal?.addEventListener('abort', () => reject(init.signal?.reason)) + ) + ]) + }) +}) + +afterEach(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() + vi.useRealTimers() +}) + +describe('refresh failures that must keep the sign-in', () => { + it.each([ + ['403 HTML from a proxy, CDN, WAF or IAM layer', () => reply(403, HTML_403, 'text/html')], + ['403 JSON', () => reply(403, '{"error":"forbidden"}')], + ['401 HTML from a proxy', () => reply(401, HTML_403, 'text/html')], + ['401 JSON without the refresh-token verdict', () => reply(401, '{"error":"invalid_token"}')], + [ + '401 JSON verdict served as HTML', + () => reply(401, '{"error":"invalid_refresh_token"}', 'text/html') + ], + ['429 rate limited', () => reply(429, '{"error":"rate_limited"}')], + ['502 HTML', () => reply(502, HTML_502, 'text/html')], + ['503 JSON', () => reply(503, '{"error":"unavailable"}')] + ])('%s', async (_name, response) => { + const active = signedIn() + answerRefresh = async () => response() + + await settle(readFreshOrcaCloudSession(config, active, '/user-data')) + + expect(store.signedOut).toBe(0) + expect(store.session).not.toBeNull() + }) +}) + +describe('refresh rejections that end the sign-in', () => { + it.each(['signed_out', 'revoked', 'expired', 'reused', undefined])( + '401 invalid_refresh_token, reason %s', + async (reason) => { + const active = signedIn() + answerRefresh = async () => + reply(401, JSON.stringify({ error: 'invalid_refresh_token', reason })) + + const result = await settle(readFreshOrcaCloudSession(config, active, '/user-data')) + + expect(result).toEqual({ status: 'reconnect-required' }) + expect(store.signedOut).toBe(1) + } + ) +}) + +describe('a refresh the server committed but answered too slowly', () => { + it('resolves inside the rotation grace instead of replaying the token after it', async () => { + const active = signedIn() + const rotations = new Map() + answerRefresh = async (refreshToken) => { + const prior = rotations.get(refreshToken) + if (prior) { + return Date.now() - prior.at < SERVER_ROTATION_GRACE_MS + ? sessionReply(prior.next) + : reply(401, '{"error":"invalid_refresh_token","reason":"reused"}') + } + rotations.set(refreshToken, { at: Date.now(), next: 'refresh-next' }) + return new Promise(() => undefined) + } + + const result = await settle(readFreshOrcaCloudSession(config, active, '/user-data')) + + expect(result).toMatchObject({ status: 'found', session: { refreshToken: 'refresh-next' } }) + expect(store.signedOut).toBe(0) + expect(refreshCalls).toBe(2) + }) +}) + +describe('operations wrapped in a fresh session', () => { + it('keeps the sign-in when the operation still answers 401 after a successful refresh', async () => { + const active = signedIn(false) + answerRefresh = async () => sessionReply('refresh-next') + + const result = runWithFreshOrcaCloudSession(config, active, '/user-data', async () => { + throw new OrcaCloudRequestError(401) + }) + + await expect(result).rejects.toBeInstanceOf(OrcaCloudRequestError) + expect(store.signedOut).toBe(0) + expect(store.session?.refreshToken).toBe('refresh-next') + }) + + it('does not rotate the token when the operation answers 403', async () => { + const active = signedIn(false) + answerRefresh = async () => sessionReply('refresh-next') + + const result = runWithFreshOrcaCloudSession(config, active, '/user-data', async () => { + throw new OrcaCloudRequestError(403) + }) + + await expect(result).rejects.toMatchObject({ statusCode: 403 }) + expect(refreshCalls).toBe(0) + }) + + it('rotates once for concurrent and repeated 401s within the backoff window', async () => { + const active = signedIn(false) + let rotation = 0 + answerRefresh = async () => sessionReply(`refresh-next-${++rotation}`) + const rejectedCall = (): Promise => + runWithFreshOrcaCloudSession(config, active, '/user-data', async () => { + throw new OrcaCloudRequestError(401) + }).catch((error: unknown) => error) + + const concurrent = await Promise.all([rejectedCall(), rejectedCall(), rejectedCall()]) + await vi.advanceTimersByTimeAsync(60_000) + const repeated = [await rejectedCall(), await rejectedCall()] + + for (const error of [...concurrent, ...repeated]) { + expect(error).toMatchObject({ statusCode: 401 }) + } + expect(refreshCalls).toBe(1) + expect(store.signedOut).toBe(0) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-session-refresh.ts b/src/main/orca-profiles/profile-cloud-session-refresh.ts index 3008dcaecd9..77b7cfa11de 100644 --- a/src/main/orca-profiles/profile-cloud-session-refresh.ts +++ b/src/main/orca-profiles/profile-cloud-session-refresh.ts @@ -8,6 +8,7 @@ import { } from './profile-cloud-client' import type { OrcaCloudSessionExchangeResponse } from './profile-cloud-session-exchange' import { + AMBIGUOUS_REFRESH_REPLAY_DELAY_MS, AmbiguousRefreshReplayBlockedError, blocksAmbiguousRefreshReplay, forgetAmbiguousRefreshAttempt, @@ -36,9 +37,31 @@ function shouldRefreshCloudSession(session: OrcaCloudSession, now = Date.now()): return session.expiresAt <= now + CLOUD_SESSION_REFRESH_SKEW_MS } -export function isOrcaCloudAuthFailure(error: unknown): boolean { +// A 403 is a permission answer, never an expired token, so only a 401 may force a refresh. +function isAccessTokenRejected(error: unknown): boolean { + return error instanceof OrcaCloudRequestError && error.statusCode === 401 +} + +// An operation that keeps answering 401 must not rotate the token on every call. +const FORCED_REFRESH_BACKOFF_MS = 5 * 60_000 +const lastForcedRefreshAt = new Map() + +function takeForcedRefreshSlot(key: string, now = Date.now()): boolean { + const last = lastForcedRefreshAt.get(key) + // A clock rollback must not stretch the backoff. + if (last !== undefined && now >= last && now - last < FORCED_REFRESH_BACKOFF_MS) { + return false + } + lastForcedRefreshAt.set(key, now) + return true +} + +// Only the auth server's own verdict may discard a sign-in; proxies, outages and limits never do. +function isRefreshTokenRejected(error: unknown): boolean { return ( - error instanceof OrcaCloudRequestError && (error.statusCode === 401 || error.statusCode === 403) + error instanceof OrcaCloudRequestError && + error.statusCode === 401 && + error.errorCode === 'invalid_refresh_token' ) } @@ -67,12 +90,8 @@ function clearCloudSessionIfUnchanged( function warnIfPossibleRefreshReplay( profileId: string, userDataPath: string, - failed: OrcaCloudSession, - error: unknown + failed: OrcaCloudSession ): void { - if (!(error instanceof OrcaCloudRequestError) || error.statusCode !== 401) { - return - } const key = orcaCloudSessionKey(profileId, userDataPath) if (!wasRefreshTokenAmbiguouslyAttempted(key, failed.refreshToken)) { return @@ -107,19 +126,19 @@ async function attemptCloudSessionRefresh( if (ambiguous) { recordAmbiguousRefreshAttempt(key, session.refreshToken) } - // Retry only explicit 5xx rejection; ambiguous failures may have spent the token. - const retryable = !ambiguous && attempt === 0 && isRetryableCloudRefreshRejection(error) - if (!ambiguous && !retryable) { + if (attempt > 0 || (!ambiguous && !isRetryableCloudRefreshRejection(error))) { throw error } + // An unanswered attempt may have rotated the token; replay it once while the server's + // rotation grace still returns the successor, instead of after the grace treats it as reuse. + if (ambiguous) { + await new Promise((resolve) => setTimeout(resolve, AMBIGUOUS_REFRESH_REPLAY_DELAY_MS)) + } // Reuse concurrent rotations instead of replaying the now-spent token. const current = readCloudSession(active.profile.id, userDataPath) if (current.status === 'found' && current.session.refreshToken !== session.refreshToken) { return { status: 'rotated-elsewhere', session: current.session } } - if (ambiguous) { - throw error - } } } } @@ -198,8 +217,8 @@ export async function readFreshOrcaCloudSession( session: await refreshStoredCloudSession(config, active, userDataPath, session.session) } } catch (error) { - if (isOrcaCloudAuthFailure(error)) { - warnIfPossibleRefreshReplay(active.profile.id, userDataPath, session.session, error) + if (isRefreshTokenRejected(error)) { + warnIfPossibleRefreshReplay(active.profile.id, userDataPath, session.session) clearCloudSessionIfUnchanged(active.profile.id, userDataPath, session.session) return { status: 'reconnect-required' } } @@ -219,8 +238,8 @@ export async function forceRefreshOrcaCloudSession( session: await refreshStoredCloudSession(config, active, userDataPath, session) } } catch (error) { - if (isOrcaCloudAuthFailure(error)) { - warnIfPossibleRefreshReplay(active.profile.id, userDataPath, session, error) + if (isRefreshTokenRejected(error)) { + warnIfPossibleRefreshReplay(active.profile.id, userDataPath, session) clearCloudSessionIfUnchanged(active.profile.id, userDataPath, session) return { status: 'reconnect-required' } } @@ -241,7 +260,15 @@ export async function runWithFreshOrcaCloudSession( try { return { status: 'ok', value: await operation(session.session) } } catch (error) { - if (!isOrcaCloudAuthFailure(error)) { + if (!isAccessTokenRejected(error)) { + throw error + } + // Reuse a rotation that already happened or is in flight; start a new one only once per backoff. + const key = orcaCloudSessionKey(active.profile.id, userDataPath) + const stored = readCloudSession(active.profile.id, userDataPath) + const rotatedSince = + stored.status === 'found' && stored.session.refreshToken !== session.session.refreshToken + if (!rotatedSince && !inflightCloudSessionRefreshes.has(key) && !takeForcedRefreshSlot(key)) { throw error } const refreshed = await forceRefreshOrcaCloudSession( @@ -253,15 +280,7 @@ export async function runWithFreshOrcaCloudSession( if (refreshed.status !== 'found') { return { status: 'reconnect-required' } } - try { - return { status: 'ok', value: await operation(refreshed.session) } - } catch (retryError) { - // Post-refresh 401 rejects the session; permission-only 403 must preserve it. - if (retryError instanceof OrcaCloudRequestError && retryError.statusCode === 401) { - clearCloudSessionIfUnchanged(active.profile.id, userDataPath, refreshed.session) - return { status: 'reconnect-required' } - } - throw retryError - } + // The auth server just accepted this session, so a second rejection is the operation's error. + return { status: 'ok', value: await operation(refreshed.session) } } } diff --git a/src/main/orcad/orcad-client-page-commands.ts b/src/main/orcad/orcad-client-page-commands.ts index 9afc3d95ab7..11e8e8e4a1e 100644 --- a/src/main/orcad/orcad-client-page-commands.ts +++ b/src/main/orcad/orcad-client-page-commands.ts @@ -28,6 +28,11 @@ import { type BrowserEngineTabs } from '../runtime/browser/client-pages/browser-client-page-queries' +import { + findListedBrowserTab, + readBrowserTabAnnotations +} from '../runtime/browser/tabs/browser-tab-annotations' + type Forward = (args: unknown[], name?: string) => unknown const LOGICAL_TAB_QUERIES = [ @@ -70,6 +75,16 @@ export function orcadClientPageCommand( : closeBrowserPageWithoutEngine(host, params, browserUnavailableError) } } + if (name === 'browserTabAnnotations') { + return async (...args: Parameters) => { + const { page, worktree } = args[0] ?? {} + // The engine's active flags are global, so a worktree's current tab needs its own query. + const tab = page + ? findListedBrowserTab((await logicalTabs().browserTabList({ worktree })).tabs, page) + : (await logicalTabs().browserTabCurrent({ worktree })).tab + return readBrowserTabAnnotations(host, tab) + } + } const query = LOGICAL_TAB_QUERIES.find((candidate) => candidate === name) if (query) { return (...args: unknown[]) => { diff --git a/src/main/rate-limits/providers/minimax/minimax-request-context.test.ts b/src/main/rate-limits/providers/minimax/minimax-request-context.test.ts index c4addf7a72c..68fc9ef7b35 100644 --- a/src/main/rate-limits/providers/minimax/minimax-request-context.test.ts +++ b/src/main/rate-limits/providers/minimax/minimax-request-context.test.ts @@ -1,27 +1,6 @@ -import { describe, expect, it, vi } from 'vitest' -import type { Session } from 'electron' -import { setMainHttpClient } from '../../../network/http-client' - -const { fetchMock, sessionFromPartitionMock } = vi.hoisted(() => { - const fetchMock = vi.fn() - const cookiesSetMock = vi.fn(() => Promise.resolve()) - const clearStorageDataMock = vi.fn(() => Promise.resolve()) - const sessionFromPartitionMock = vi.fn(() => ({ - clearStorageData: clearStorageDataMock, - cookies: { set: cookiesSetMock }, - fetch: fetchMock - })) - return { clearStorageDataMock, cookiesSetMock, fetchMock, sessionFromPartitionMock } -}) +import { describe, expect, it } from 'vitest' import { redactMiniMaxSecret } from './minimax-request-context' -setMainHttpClient({ - fetch: fetchMock, - proxySession: () => null, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the code under test only calls clearStorageData, cookies.set and fetch, which the fake provides. - partitionSession: sessionFromPartitionMock as unknown as (partition: string) => Session -}) - describe('redactMiniMaxSecret', () => { it('redacts _token values in header and quoted syntax', () => { const redacted = redactMiniMaxSecret('cookie _token=eyJhABCDEF and _token:"x.y"') diff --git a/src/main/repository-icons/repo-icon-autodetect.ts b/src/main/repository-icons/repo-icon-autodetect.ts index 64dce61e202..393672a9ef9 100644 --- a/src/main/repository-icons/repo-icon-autodetect.ts +++ b/src/main/repository-icons/repo-icon-autodetect.ts @@ -8,7 +8,7 @@ import { githubAvatarSlug, type RepoIcon } from '../../shared/repo-icon' -import { getRepoSlug, getRepoUpstream } from '../github/client/fetch/repo-slug-upstream' +import { getRepoSlug } from '../github/client/fetch/repo-slug-upstream' import { resolveFilesystemRouteForHost, resolveGitRouteForHost @@ -92,6 +92,24 @@ export async function detectGitHubAvatarIcon( } } +async function detectRepoLocalIcon( + repoPath: string, + executionHostId: ExecutionHostId +): Promise { + try { + const route = resolveFilesystemRouteForHost(executionHostId) + const fileIcon = await detectRepoFileIcon(repoPath, route) + if (fileIcon) { + return fileIcon + } + return ( + (route.kind === 'local' ? await detectLocalPackageHomepageIcon(repoPath) : null) ?? undefined + ) + } catch { + return undefined + } +} + export async function detectRepoIcon({ repoPath, kind, @@ -103,30 +121,15 @@ export async function detectRepoIcon({ executionHostId: ExecutionHostId upstream?: GitHubRepositoryIdentity | null }): Promise { - try { - const route = resolveFilesystemRouteForHost(executionHostId) - const fileIcon = await detectRepoFileIcon(repoPath, route) - if (fileIcon) { - return fileIcon - } - - const homepageIcon = - route.kind === 'local' ? await detectLocalPackageHomepageIcon(repoPath) : null - if (homepageIcon) { - return homepageIcon - } - - if (kind === 'git') { - return (await detectGitHubAvatarIcon(repoPath, executionHostId, upstream)) ?? undefined - } - } catch { - // Icon failures must not prevent repo creation. - } - return undefined + return ( + (await detectRepoLocalIcon(repoPath, executionHostId)) ?? + (kind === 'git' + ? ((await detectGitHubAvatarIcon(repoPath, executionHostId, upstream)) ?? undefined) + : undefined) + ) } -// A null upstream marks a resolved non-fork and prevents repeated probes. -export async function detectRepoIconAndUpstream({ +export async function detectRepoLocalMetadata({ repoPath, kind, executionHostId @@ -135,22 +138,13 @@ export async function detectRepoIconAndUpstream({ kind: RepoKind executionHostId: ExecutionHostId }) { - const remoteRead = repoRemoteReadConnection(executionHostId) - const upstream = - kind === 'git' && remoteRead.kind === 'dial' - ? await getRepoUpstream(repoPath, remoteRead.connectionId) - : null const gitRemoteIdentity = kind === 'git' - ? await detectGitRemoteIdentity(repoPath, executionHostId, { - // Host Git on purpose: this runs while the project is being added, before it exists. - hostGit: true - }) + ? await detectGitRemoteIdentity(repoPath, executionHostId, { hostGit: true }) : null - const repoIcon = await detectRepoIcon({ repoPath, kind, executionHostId, upstream }) + const repoIcon = await detectRepoLocalIcon(repoPath, executionHostId) return { ...(repoIcon ? { repoIcon } : {}), - ...(gitRemoteIdentity ? { gitRemoteIdentity } : {}), - ...(kind === 'git' ? { upstream: upstream ?? null } : {}) + ...(gitRemoteIdentity ? { gitRemoteIdentity } : {}) } } diff --git a/src/main/runtime/browser/commands/browser-command-contracts.ts b/src/main/runtime/browser/commands/browser-command-contracts.ts index 9d5367bf3b9..09d04d459ce 100644 --- a/src/main/runtime/browser/commands/browser-command-contracts.ts +++ b/src/main/runtime/browser/commands/browser-command-contracts.ts @@ -9,6 +9,7 @@ import type { BrowserBackend } from '../../../browser/browser-backend' import type { BrowserSessionTabSelectionOptions } from '../tabs/browser-tab-create-publication' import type { ServeBrowserTabs } from '../headless/serve-browser-tabs' import type { BrowserTabBarEntry } from '../tabs/browser-tab-listing' +import type { BrowserPageAnnotation } from '../../../../shared/browser/element-grab/browser-grab-types' export type BrowserCommandTargetParams = { worktree?: string @@ -60,6 +61,8 @@ export type RuntimeBrowserCommandHost = { options?: BrowserSessionTabSelectionOptions ): void notifyHeadlessBrowserSessionTabsChanged?(worktreeId: string): void + /** A page's unsent notes; see readSavedBrowserPageAnnotations. */ + readBrowserPageAnnotations?(browserPageId: string): BrowserPageAnnotation[] /** The tab bar's browser tabs, loaded or not, from the published session snapshot. */ readBrowserTabBar?(worktreeId: string | undefined): BrowserTabBarEntry[] retireRuntimeOwnedBrowserSessionTab?(worktreeId: string, browserPageId: string): boolean | void diff --git a/src/main/runtime/browser/commands/browser-commands.ts b/src/main/runtime/browser/commands/browser-commands.ts index acdda731ff6..4f8e0cb11a8 100644 --- a/src/main/runtime/browser/commands/browser-commands.ts +++ b/src/main/runtime/browser/commands/browser-commands.ts @@ -81,6 +81,7 @@ export class RuntimeBrowserCommands { readonly browserProceedCertificate: RuntimeBrowserTabQueries['browserProceedCertificate'] readonly browserTabShow: RuntimeBrowserTabQueries['browserTabShow'] readonly browserTabCurrent: RuntimeBrowserTabQueries['browserTabCurrent'] + readonly browserTabAnnotations: RuntimeBrowserTabQueries['browserTabAnnotations'] readonly browserTabSwitch: RuntimeBrowserTabQueries['browserTabSwitch'] readonly browserTabCreate: RuntimeBrowserTabCreation['browserTabCreate'] readonly browserOpenUrlOnClient: RuntimeBrowserTabCreation['browserOpenUrlOnClient'] @@ -187,6 +188,7 @@ export class RuntimeBrowserCommands { this.browserProceedCertificate = queries.browserProceedCertificate.bind(queries) this.browserTabShow = queries.browserTabShow.bind(queries) this.browserTabCurrent = queries.browserTabCurrent.bind(queries) + this.browserTabAnnotations = queries.browserTabAnnotations.bind(queries) this.browserTabSwitch = queries.browserTabSwitch.bind(queries) this.browserTabCreate = creation.browserTabCreate.bind(creation) this.browserOpenUrlOnClient = creation.browserOpenUrlOnClient.bind(creation) diff --git a/src/main/runtime/browser/screencast/browser-screencasts.ts b/src/main/runtime/browser/screencast/browser-screencasts.ts index 192aa7412ed..d8a97faa304 100644 --- a/src/main/runtime/browser/screencast/browser-screencasts.ts +++ b/src/main/runtime/browser/screencast/browser-screencasts.ts @@ -2,6 +2,7 @@ import type { BrowserScreencastResult } from '../../../../shared/browser/runtime 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 { mintBrowserScreencastSubscriptionId } from './browser-screencast-subscription-id' import { @@ -102,6 +103,7 @@ export class RuntimeBrowserScreencasts { format: params.format, ...budget, ...viewport, + holdPaint: () => browserManager.holdPaintForCapture(guest.id), onFrame: (bytes) => { const ghosts: string[] = [] for (const [subscriptionId, subscriber] of pendingRecord.subscribers) { 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 index 6e5d0b3db0c..c87652a7309 100644 --- 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 @@ -92,6 +92,7 @@ describe('sendRemoteBrowserScreencastFrame', () => { maxHeight: 2160, everyNthFrame: 1, minFrameIntervalMs: 0, + holdPaint: () => () => {}, onFrame: (bytes) => sendRemoteBrowserScreencastFrame(transport.sendBinary, bytes) !== 'refused' }) diff --git a/src/main/runtime/browser/tabs/browser-tab-annotations.ts b/src/main/runtime/browser/tabs/browser-tab-annotations.ts new file mode 100644 index 00000000000..c58ceffb5ab --- /dev/null +++ b/src/main/runtime/browser/tabs/browser-tab-annotations.ts @@ -0,0 +1,67 @@ +import type { BrowserPageAnnotation } from '../../../../shared/browser/element-grab/browser-grab-types' +import type { + BrowserTabAnnotationsResult, + BrowserTabInfo +} from '../../../../shared/browser/runtime/runtime-browser-contracts' +import { isHostReachableDocument } from '../../../../shared/desktop-browser-bridge-protocol' +import { BrowserError } from '../../../browser/browser-error' +import type { RuntimeStore } from '../../construction/runtime-store-contract' +import type { RuntimeBrowserCommandHost } from '../commands/browser-command-contracts' +import { remoteCliBrowserScopeWorkspaceId } from '../../desktop-browser-bridge/remote-cli-browser-scope' + +/** A page's unsent notes from the saved session, which the window keeps current. */ +export function readSavedBrowserPageAnnotations( + store: + | Pick + | null + | undefined, + browserPageId: string +): BrowserPageAnnotation[] { + // Page ids are unique across hosts, and a bridged SSH page has no worktree row here. + for (const hostId of store?.getWorkspaceSessionHostIds?.() ?? []) { + const pages = store?.getWorkspaceSession?.(hostId)?.browserPagesByWorkspace ?? {} + for (const workspacePages of Object.values(pages)) { + const page = workspacePages.find((candidate) => candidate.id === browserPageId) + if (page) { + return page.annotations ?? [] + } + } + } + return [] +} + +export function findListedBrowserTab( + tabs: readonly BrowserTabInfo[], + page: string +): BrowserTabInfo { + const tab = tabs.find((candidate) => candidate.browserPageId === page) + if (!tab) { + throw new BrowserError('browser_tab_not_found', `Browser page ${page} was not found`) + } + return tab +} + +export function readBrowserTabAnnotations( + host: Pick< + RuntimeBrowserCommandHost, + 'getRuntimeBrowserPageRegistry' | 'readBrowserPageAnnotations' + >, + tab: BrowserTabInfo +): BrowserTabAnnotationsResult { + // A paired desktop draws this page and keeps its notes; this host would wrongly report none. + if (host.getRuntimeBrowserPageRegistry().getPage(tab.browserPageId)) { + throw new BrowserError( + 'browser_annotations_unavailable', + `Tab ${tab.browserPageId} is drawn by a paired desktop, which keeps its unsent notes. Ask the user to send them from that tab.` + ) + } + const annotations = host.readBrowserPageAnnotations?.(tab.browserPageId) ?? [] + return { + tab, + // An SSH host may not read what a note captured from a desktop-local document. + annotations: + remoteCliBrowserScopeWorkspaceId() === undefined + ? annotations + : annotations.filter((note) => isHostReachableDocument(note.payload.page.sanitizedUrl)) + } +} diff --git a/src/main/runtime/browser/tabs/browser-tab-queries.ts b/src/main/runtime/browser/tabs/browser-tab-queries.ts index 5aaab4a5a66..51f31bdbe76 100644 --- a/src/main/runtime/browser/tabs/browser-tab-queries.ts +++ b/src/main/runtime/browser/tabs/browser-tab-queries.ts @@ -1,4 +1,5 @@ import type { + BrowserTabAnnotationsResult, BrowserTabCurrentResult, BrowserTabListResult, BrowserTabShowResult, @@ -17,6 +18,7 @@ import type { } from '../commands/browser-command-contracts' import type { RuntimeBrowserCommandTargets } from '../commands/browser-command-targets' import type { RuntimeBrowserTabCatalog } from './browser-tab-catalog' +import { findListedBrowserTab, readBrowserTabAnnotations } from './browser-tab-annotations' export class RuntimeBrowserTabQueries { constructor( @@ -27,6 +29,7 @@ export class RuntimeBrowserTabQueries { | 'getRuntimeBrowserPageRegistry' | 'markHeadlessBrowserSessionTabActive' | 'notifyHeadlessBrowserSessionTabsChanged' + | 'readBrowserPageAnnotations' >, private readonly targets: Pick< RuntimeBrowserCommandTargets, @@ -89,6 +92,22 @@ export class RuntimeBrowserTabQueries { return { tab: this.catalog.describeBrowserTab(params.page, target.worktreeId) } } + async browserTabAnnotations(params: { + page?: string + worktree?: string + }): Promise { + if (!params.page) { + return readBrowserTabAnnotations(this.host, (await this.browserTabCurrent(params)).tab) + } + // A named page's notes are saved state: list the tab bar as saved rather than waking a browser. + const workspaceId = params.worktree + ? (await this.host.resolveBrowserWorkspace(params.worktree)).id + : undefined + const clientPages = this.host.getRuntimeBrowserPageRegistry().listPages(workspaceId) + const tabs = this.catalog.listLogicalBrowserTabs(workspaceId, clientPages) + return readBrowserTabAnnotations(this.host, findListedBrowserTab(tabs, params.page)) + } + async browserTabCurrent(params: { worktree?: string }): Promise { const tab = (await this.browserTabList(params)).tabs.find((candidate) => candidate.active) if (!tab) { diff --git a/src/main/runtime/construction/runtime-edge-command-controller.ts b/src/main/runtime/construction/runtime-edge-command-controller.ts index 933c812272c..6d6b7fac4ec 100644 --- a/src/main/runtime/construction/runtime-edge-command-controller.ts +++ b/src/main/runtime/construction/runtime-edge-command-controller.ts @@ -47,6 +47,7 @@ const BROWSER_COMMAND_NAMES = [ 'browserProceedCertificate', 'browserTabShow', 'browserTabCurrent', + 'browserTabAnnotations', 'browserTabSwitch', 'browserHover', 'browserDrag', diff --git a/src/main/runtime/construction/runtime-host-services.ts b/src/main/runtime/construction/runtime-host-services.ts index b1515e72345..38403c91120 100644 --- a/src/main/runtime/construction/runtime-host-services.ts +++ b/src/main/runtime/construction/runtime-host-services.ts @@ -1,8 +1,6 @@ import type * as Calls from './runtime-host-service-calls' import type { RuntimeConstructionBindings as HostBindings } from './runtime-construction-dependencies' -import type { RuntimeRepositoryCommandSurface } from '../repositories/runtime-repository-command-surface' - import type { LegacyWorkerRecoveryCandidate } from '../orchestration/terminal-authority/structured-sessions/runtime-legacy-worker-terminal-recovery-types' import type { LegacyWorkerTerminalRecoveryPlan } from '../orchestration/terminal-authority/release/orchestration-legacy-worker-terminal-recovery' @@ -46,8 +44,6 @@ import { teardownFolderWorkspacePtys } from '../workspaces/removal/folder-worksp import { countRepoTerminalsNotKnownExited } from '../workspaces/removal/project-removal-impact' export abstract class OrcaRuntimeWithPreservedBranchCleanup extends OrcaRuntimeWithTerminalDrivers { - declare addRepo: RuntimeRepositoryCommandSurface['addRepo'] - declare cloneRepo: RuntimeRepositoryCommandSurface['cloneRepo'] declare acquireFileWatcherRemoval: ConstructorParameters< typeof RuntimeProjectGroupController >[0]['acquireFileWatcherRemoval'] @@ -279,8 +275,11 @@ export abstract class OrcaRuntimeWithPreservedBranchCleanup extends OrcaRuntimeW protected readonly projectHostSetups = new RuntimeProjectHostSetupController({ getStore: () => this.store, listRepos: () => this.listRepos(), - addRepo: (path, kind, hostId) => this.addRepo(path, kind, hostId), - cloneRepo: (args) => this.cloneRepo(args.url, args.destination, args.hostId, args.folderName), + addRepo: (path, kind, hostId) => this.repositoryRegistrations.add(path, kind, hostId), + cloneRepo: (args) => + this.repositoryClones.clone(args.url, args.destination, args.hostId, args.folderName), + resolveRepositoryMetadata: (repo) => this.repositoryForkBackfill.resolve(repo), + enqueueRepositoryMetadata: (repos) => void this.repositoryForkBackfill.enqueue(repos), invalidateResolvedWorktrees: () => this.invalidateResolvedWorktreeCache(), invalidateWorktreeScan: (repoId) => this.invalidateWorktreeScanCacheForRepo(repoId), notifyReposChanged: () => this.notifyReposChanged(), @@ -353,7 +352,7 @@ export abstract class OrcaRuntimeWithPreservedBranchCleanup extends OrcaRuntimeW protected readonly serverEnvironment = new RuntimeServerEnvironmentCommands() - protected readonly repositoryForkBackfill = new RuntimeRepositoryForkBackfill( + readonly repositoryForkBackfill = new RuntimeRepositoryForkBackfill( () => this.store, () => this.notifyReposChanged() ) diff --git a/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-registry.test.ts b/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-registry.test.ts index cc2170d60e7..4338bf8352b 100644 --- a/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-registry.test.ts +++ b/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-registry.test.ts @@ -6,6 +6,28 @@ import { } from './desktop-browser-bridge-registry' import { routeDesktopBrowserBridgeRpc } from './desktop-browser-bridge-route' +describe('tab annotations through the desktop bridge', () => { + it('never sends them to an older desktop, which would drop its whole bridge', async () => { + const registry = new DesktopBrowserBridgeRegistry() + const emit = vi.fn() + registry.attach({ connectionId: 'new', pairedDeviceId: 'd', readsTabAnnotations: true, emit }) + registry.attach({ connectionId: 'old', pairedDeviceId: 'd', emit }) + + await expect( + routeDesktopBrowserBridgeRpc({ + method: 'browser.tabAnnotations', + params: { page: 'page-1' }, + caller: { kind: 'local-cli' }, + hostEnabled: true, + registry, + localBrowserAvailable: false, + resolveWorkspace: async (selector) => ({ id: selector }) + }) + ).rejects.toMatchObject({ code: 'desktop_browser_bridge_not_forwarded' }) + expect(emit).not.toHaveBeenCalled() + }) +}) + describe('--expect-url through the desktop bridge', () => { const route = (registry: DesktopBrowserBridgeRegistry) => routeDesktopBrowserBridgeRpc({ diff --git a/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-registry.ts b/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-registry.ts index b0c561e52ef..b297f8e6d2b 100644 --- a/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-registry.ts +++ b/src/main/runtime/desktop-browser-bridge/desktop-browser-bridge-registry.ts @@ -19,6 +19,7 @@ type Attachment = { pairedDeviceId: string acceptsCancel?: boolean enforcesExpectUrl?: boolean + readsTabAnnotations?: boolean emit: (event: DesktopBrowserBridgeEvent) => void } @@ -57,6 +58,10 @@ export class DesktopBrowserBridgeRegistry { return this.attachments.at(-1)?.enforcesExpectUrl === true } + newestAttachmentReadsTabAnnotations(): boolean { + return this.attachments.at(-1)?.readsTabAnnotations === true + } + forward( request: DesktopBrowserBridgeForward, options: { timeoutMs: number; signal?: AbortSignal } 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 ae0f6a6aaa5..2f472b5f36e 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 @@ -75,6 +75,15 @@ export async function routeDesktopBrowserBridgeRpc(options: { 'The Orca desktop sharing its browser cannot check --expect-url. Update Orca on that desktop or drop the flag.' ) } + if ( + forwardedMethod === 'browser.tabAnnotations' && + !options.registry.newestAttachmentReadsTabAnnotations() + ) { + throw new BrowserError( + DESKTOP_BROWSER_BRIDGE_NOT_FORWARDED_CODE, + 'The Orca desktop sharing its browser cannot read tab notes. Update Orca on that desktop.' + ) + } const result = await options.registry.forward( { method: forwardedMethod, params, ...(workspaceId ? { workspaceId } : {}) }, { timeoutMs: forwardTimeoutMs(forwardedMethod, params), signal: options.signal } diff --git a/src/main/runtime/hosts/runtime-status.ts b/src/main/runtime/hosts/runtime-status.ts index 7800d47fea3..73dc3dea758 100644 --- a/src/main/runtime/hosts/runtime-status.ts +++ b/src/main/runtime/hosts/runtime-status.ts @@ -45,7 +45,7 @@ import { TERMINAL_PERSISTENCE_UNAVAILABLE_MESSAGE } from '../../../shared/runtime-capability-degradation' import { MOBILE_WEB_BUNDLE_CAPABILITY } from '../../../shared/mobile-web-bundle/mobile-web-bundle-capability' -import { loadBundledMobileWebBundle } from '../rpc/methods/mobile-delivery/bundled-mobile-web-bundle' +import { getBundledMobileWebBundleRoot } from '../rpc/methods/mobile-delivery/bundled-mobile-web-bundle' import { runtimeTerminalDegradation } from '../terminal/launch/native-terminal-availability' import { isWindowsProcessStartTimeAvailable } from '../../windows/windows-process-table' import { WORKTREE_CREATE_RESULT_TTL_MS } from '../workspaces/creation/worktree-create-idempotency' @@ -120,8 +120,8 @@ export abstract class OrcaRuntimeWithGetStatus extends RuntimeWorkspaceChangeEve capabilities.push(DESKTOP_BROWSER_BRIDGE_RUNTIME_CAPABILITY) } capabilities.push(...darkSwitchRuntimeCapabilities()) - // Dev/serve installs may lack out/mobile-web; never advertise downloads this install cannot produce. - if (loadBundledMobileWebBundle()) { + // Dev/serve installs may lack out/mobile-web; advertise downloads only where the install ships it. + if (getBundledMobileWebBundleRoot()) { capabilities.push(MOBILE_WEB_BUNDLE_CAPABILITY) } // Report the actual failure so operators are not told to fix already-correct configuration. diff --git a/src/main/runtime/mobile-cloud-relay/relay-session-broker.ts b/src/main/runtime/mobile-cloud-relay/relay-session-broker.ts index 78f99af7c05..d7be7f45381 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-session-broker.ts +++ b/src/main/runtime/mobile-cloud-relay/relay-session-broker.ts @@ -19,6 +19,7 @@ import { relayIdentityKey } from './relay-auth-identity' import { RelayOriginPool } from './relay-origin-pool' import { RelayRegionRefresh } from './relay-region-refresh' import { relayRenewalDelayMs } from './relay-renewal-jitter' +import { RelayWallClockTimer } from './relay-wall-clock-timer' export class RelaySessionBroker { private readonly options: RelaySessionBrokerOptions @@ -26,11 +27,12 @@ export class RelaySessionBroker { private readonly originPool: RelayOriginPool private readonly regionRefresh: RelayRegionRefresh | null private authorization: RelayAuthorization | null = null - private refreshTimer: ReturnType | null = null + private readonly refreshTimer: RelayWallClockTimer private closed = false private constructor(options: RelaySessionBrokerOptions) { this.options = options + this.refreshTimer = new RelayWallClockTimer(options.now) this.relayHostId = deriveRelayHostId(options.keypair.publicKey) this.originPool = new RelayOriginPool({ directorUrl: options.authConfig.relayDirectorUrl, @@ -199,10 +201,7 @@ export class RelaySessionBroker { } const publishOffline = this.options.isCurrent() this.closed = true - if (this.refreshTimer) { - clearTimeout(this.refreshTimer) - this.refreshTimer = null - } + this.refreshTimer.cancel() this.originPool.closeNow(hostCloseReason) this.regionRefresh?.close() if (publishOffline) { @@ -259,11 +258,10 @@ export class RelaySessionBroker { const now = (this.options.now ?? Date.now)() const random = this.options.random ?? Math.random const delay = relayRenewalDelayMs(authorization.expiresAt, now, random) - this.refreshTimer = setTimeout(() => void this.refreshAuthorization(), delay) + this.refreshTimer.schedule(delay, () => void this.refreshAuthorization()) } private async refreshAuthorization(): Promise { - this.refreshTimer = null try { const refresh = await this.options.refreshAccessToken() this.assertCurrent() @@ -287,9 +285,9 @@ export class RelaySessionBroker { const now = (this.options.now ?? Date.now)() if (!this.closed && this.options.isCurrent() && now <= expiry + 60_000) { const random = this.options.random ?? Math.random - this.refreshTimer = setTimeout( - () => void this.refreshAuthorization(), - 5_000 + Math.floor(random() * 10_001) + this.refreshTimer.schedule( + 5_000 + Math.floor(random() * 10_001), + () => void this.refreshAuthorization() ) return } 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 new file mode 100644 index 00000000000..531ee347220 --- /dev/null +++ b/src/main/runtime/mobile-cloud-relay/relay-wall-clock-timer.test.ts @@ -0,0 +1,78 @@ +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) + }) + + it('re-arms from the wall clock when the machine resumes before the task is due', () => { + 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) + // A 60 s sleep: the timer clock lost it, so 120 s of wall time are left. + wall += 60_000 + source.resume() + expect(task).not.toHaveBeenCalled() + vi.advanceTimersByTime(119_000) + expect(task).not.toHaveBeenCalled() + vi.advanceTimersByTime(1_000) + expect(task).toHaveBeenCalledTimes(1) + vi.advanceTimersByTime(180_000) + expect(task).toHaveBeenCalledTimes(1) + }) + + it('does not run a due task on the state report at subscribe, and never after cancel', () => { + vi.useFakeTimers() + const source = resumeSource() + const timer = new RelayWallClockTimer(() => 0, source.subscribe) + const task = vi.fn() + timer.schedule(0, task) + expect(task).not.toHaveBeenCalled() + timer.cancel() + source.resume() + vi.advanceTimersByTime(1_000) + expect(task).not.toHaveBeenCalled() + expect(source.count()).toBe(0) + }) +}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-wall-clock-timer.ts b/src/main/runtime/mobile-cloud-relay/relay-wall-clock-timer.ts new file mode 100644 index 00000000000..da84d170f86 --- /dev/null +++ b/src/main/runtime/mobile-cloud-relay/relay-wall-clock-timer.ts @@ -0,0 +1,68 @@ +import { subscribeSystemPowerLifecycle } from '../../power/system-power-lifecycle' + +type SubscribeResume = (onResume: () => void) => () => void + +const subscribeResume: SubscribeResume = (onResume) => + subscribeSystemPowerLifecycle({ onSuspend: () => {}, onResume }) + +// A one-shot timer due at a wall-clock time. Node timers run on a clock that stops while the +// machine sleeps, so a relay token renewal due during a sleep would fire that much later after +// wake, after the token's wall-clock expiry: the relay then closes the still-live control 4401. +// On resume, a task already due runs at once; one not yet due is re-armed from the wall clock. +export class RelayWallClockTimer { + private timer: ReturnType | null = null + private unsubscribe: (() => void) | null = null + private dueAt = 0 + private task: (() => void) | null = null + + constructor( + private readonly now: () => number = Date.now, + private readonly onResume: SubscribeResume = subscribeResume + ) {} + + schedule(delayMs: number, task: () => void): void { + this.cancel() + this.dueAt = this.now() + delayMs + this.task = task + this.arm(delayMs) + // The lifecycle reports the current state on subscribe; only later resumes count. On each + // resume a due task runs, and one not yet due is re-armed for the time left on the wall clock + // (the timer clock lost the whole sleep). + let subscribed = false + this.unsubscribe = this.onResume(() => { + if (!subscribed || this.task !== task) { + return + } + const left = this.dueAt - this.now() + if (left <= 0) { + this.fire() + } else { + this.arm(left) + } + }) + subscribed = true + } + + cancel(): void { + if (this.timer) { + clearTimeout(this.timer) + this.timer = null + } + this.unsubscribe?.() + this.unsubscribe = null + this.task = null + } + + private arm(delayMs: number): void { + if (this.timer) { + clearTimeout(this.timer) + } + this.timer = setTimeout(() => this.fire(), delayMs) + } + + private fire(): void { + const task = this.task + this.cancel() + task?.() + } +} 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 a141ece1665..6251a4fca06 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 @@ -1,9 +1,9 @@ import { realpathSync } from 'node:fs' -import { describe, expect, it } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' import { execFileSync } from 'node:child_process' -import { getRepoUpstreamMock } from '../orca-runtime-test-mocks/setup.spec' +import * as forkMetadata from '../../github/client/fetch/repo-slug-upstream' import { join } from 'node:path' import { mkdtemp, rm } from 'node:fs/promises' import { projectHostSetupProjectionFromRepos } from '../../../shared/project-host-setup-projection' @@ -12,6 +12,11 @@ import { store } from './orca-runtime-test-fixtures.spec' import type { Repo } from '../../../shared/repo-types' import type { RuntimeStore } from '../construction/runtime-store-contract' +const parentProbe = vi.spyOn(forkMetadata, 'probeRepoUpstream') +beforeEach(() => { + parentProbe.mockReset().mockResolvedValue({ upstream: undefined, origin: null }) +}) + function createRuntime(repos: Repo[]): OrcaRuntimeService { const runtimeStore: RuntimeStore = { ...store, @@ -61,7 +66,6 @@ const repoA = { provider: 'github' as const, owner: 'acme', repo: 'repo-a' } describe('OrcaRuntimeService project setup of an existing folder (#30663)', () => { it('refuses to relabel a folder whose own GitHub remote names another repository', async () => { const repos: Repo[] = [] - getRepoUpstreamMock.mockResolvedValueOnce(null) const runtime = createRuntime(repos) await withGitFolder({ origin: 'https://github.com/acme/repo-b.git' }, async (path) => { @@ -118,3 +122,447 @@ describe('OrcaRuntimeService project setup of an existing folder (#30663)', () = ) }) }) + +describe('explicit fork project setup with deferred ordinary metadata', () => { + it.each([ + ['git@gh-personal:me/repo-a.git', 'github:me/repo-a', undefined, null], + [ + 'https://code.corp.example/me/repo-a.git', + 'github:code.corp.example/me/repo-a', + 'code.corp.example', + undefined + ] + ] as const)( + 'keeps a resolved origin nonfork through setup when its local hostname needs resolution: %s', + async (url, projectId, host, upstream) => { + const repos: Repo[] = [] + const origin = { owner: 'me', repo: 'repo-a', ...(host ? { host } : {}) } + parentProbe.mockResolvedValue({ upstream, origin }) + const runtime = createRuntime(repos) + await withGitFolder({ origin: url }, async (path) => { + const result = await runtime.setupProjectExistingFolder({ + projectId, + projectProviderIdentity: { provider: 'github', ...origin }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + expect(result.project.id).toBe(projectId) + expect(result.repo.upstream).toBeNull() + expect( + projectHostSetupProjectionFromRepos(JSON.parse(JSON.stringify(repos))).setups[0].projectId + ).toBe(projectId) + expect(parentProbe).toHaveBeenCalledTimes(1) + }) + } + ) + + 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.each([null, undefined])( + 'keeps a matching origin nonfork when parent evidence is %s', + async (upstream) => { + const repos: Repo[] = [] + parentProbe.mockResolvedValue({ upstream, 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: 'github:me/repo-a', + projectProviderIdentity: { provider: 'github', owner: 'me', repo: 'repo-a' }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + expect(result.project.id).toBe('github:me/repo-a') + expect(result.repo.upstream).toBeNull() + expect( + projectHostSetupProjectionFromRepos(JSON.parse(JSON.stringify(repos))).setups[0].projectId + ).toBe('github:me/repo-a') + expect(parentProbe).toHaveBeenCalledTimes(1) + const again = await runtime.setupProjectExistingFolder({ + projectId: 'github:me/repo-a', + projectProviderIdentity: { provider: 'github', owner: 'me', repo: 'repo-a' }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + expect(again.repo.upstream).toBeNull() + 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[] = [ + { + id: 'blocker', + path: '/blocked', + displayName: 'blocker', + badgeColor: 'blue', + addedAt: 1, + kind: 'git' + } + ] + const runtime = createRuntime(repos) + const gate = Promise.withResolvers() + parentProbe + .mockImplementationOnce(() => gate.promise) + .mockResolvedValue({ + upstream: { owner: 'acme', repo: 'repo-a' }, + origin: { owner: 'me', repo: 'repo-a' } + }) + const background = runtime.repositoryForkBackfill.enqueue(repos) + try { + const result = await runtime.setupProjectExistingFolder({ + projectId: 'github:acme/repo-a', + projectProviderIdentity: repoA, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + expect(result.project.id).toBe('github:acme/repo-a') + expect(repos[0].upstream).toBeUndefined() + expect(parentProbe).toHaveBeenCalledTimes(2) + } finally { + gate.resolve({ upstream: null, origin: null }) + await background + } + }) +}) + +it.each([false, true])( + 'refuses changed current origin after an unavailable lookup (pre-existing=%s)', + async (existing) => { + await withGitFolder({ origin: 'https://github.com/me/repo-a.git' }, async (path) => { + const repos: Repo[] = [] + if (existing) { + repos.push({ + id: 'selected', + path: realpathSync(path), + displayName: 'repo-a', + badgeColor: 'blue', + addedAt: 1, + kind: 'git', + executionHostId: 'runtime:env-1', + gitRemoteIdentity: { + canonicalKey: 'github.com/me/repo-a', + remoteName: 'origin', + remoteUrl: 'https://github.com/me/repo-a.git' + } + }) + } + const runtime = createRuntime(repos) + const gate = Promise.withResolvers() + const started = Promise.withResolvers() + parentProbe.mockImplementationOnce(() => { + started.resolve() + return gate.promise + }) + const setup = runtime.setupProjectExistingFolder({ + projectId: 'github:me/repo-a', + projectProviderIdentity: { provider: 'github', owner: 'me', repo: 'repo-a' }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + const rejection = expect(setup).rejects.toThrow(/points at other\/repo-a, not me\/repo-a/) + await started.promise + execFileSync('git', ['remote', 'set-url', 'origin', 'https://github.com/other/repo-a.git'], { + cwd: path, + stdio: 'ignore' + }) + gate.resolve({ upstream: undefined, origin: { owner: 'me', repo: 'repo-a' } }) + await rejection + expect(repos).toHaveLength(existing ? 1 : 0) + expect(parentProbe).toHaveBeenCalledTimes(1) + }) + } +) + +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[] = [] + const runtime = createRuntime(repos) + const gate = Promise.withResolvers() + const started = Promise.withResolvers() + parentProbe.mockImplementationOnce(() => { + started.resolve() + return gate.promise + }) + const setup = runtime.setupProjectExistingFolder({ + projectId: 'github:me/repo-a', + projectProviderIdentity: { provider: 'github', owner: 'me', repo: 'repo-a' }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + await started.promise + execFileSync('git', ['remote', 'set-url', 'origin', 'https://github.com/other/repo-a.git'], { + cwd: path, + stdio: 'ignore' + }) + gate.resolve({ upstream: null, origin: { owner: 'me', repo: 'repo-a' } }) + const result = await setup + expect(result.project.id).toBe('github:me/repo-a') + expect(result.repo.upstream).toBeNull() + expect( + projectHostSetupProjectionFromRepos(JSON.parse(JSON.stringify(repos))).setups[0].projectId + ).toBe('github:me/repo-a') + }) +}) + +it('publishes metadata retained on a pre-existing row after explicit setup fails', async () => { + await withGitFolder({ origin: 'https://github.com/me/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' + } + ] + const runtime = createRuntime(repos) + parentProbe.mockResolvedValue({ + upstream: { owner: 'acme', repo: 'repo-a' }, + origin: { owner: 'me', repo: 'repo-a' } + }) + const notifications: string[] = [] + const unsubscribe = runtime.onClientEvent((event) => { + if (event.type === 'reposChanged') { + notifications.push(event.type) + } + }) + try { + await expect( + runtime.setupProjectExistingFolder({ + projectId: 'github:elsewhere/repo-a', + projectProviderIdentity: { provider: 'github', owner: 'elsewhere', repo: 'repo-a' }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + ).rejects.toThrow(/points at me\/repo-a, not elsewhere\/repo-a/) + expect(repos).toHaveLength(1) + expect(repos[0].upstream).toEqual({ owner: 'acme', repo: 'repo-a' }) + expect(notifications).toEqual(['reposChanged']) + expect(parentProbe).toHaveBeenCalledTimes(1) + } finally { + unsubscribe() + } + }) +}) + +it.each(['recovered parent', 'unavailable'] as const)( + 'settles an explicit origin after ordinary alias enrichment: %s', + async (evidence) => { + await withGitFolder({ origin: 'git@gh-personal:me/repo-a.git' }, async (path) => { + const repos: Repo[] = [] + const runtime = createRuntime(repos) + const origin = { owner: 'me', repo: 'repo-a' } + const ordinary = Promise.withResolvers() + const ordinaryStarted = Promise.withResolvers() + const ordinaryFinished = Promise.withResolvers() + const required = Promise.withResolvers() + const requiredStarted = Promise.withResolvers() + parentProbe + .mockImplementationOnce(() => { + ordinaryStarted.resolve() + return ordinary.promise + }) + .mockImplementationOnce(() => { + requiredStarted.resolve() + return required.promise + }) + const unsubscribe = runtime.onClientEvent((event) => { + if (event.type === 'reposChanged' && repos[0]?.repoIcon?.type === 'image') { + ordinaryFinished.resolve() + } + }) + try { + const added = await runtime.addRepo(path, 'git', 'runtime:env-1') + await ordinaryStarted.promise + ordinary.resolve({ upstream: undefined, origin }) + await ordinaryFinished.promise + expect(added.id).toBe(repos[0].id) + expect(repos[0].gitRemoteIdentity).toEqual({ + canonicalKey: 'gh-personal/me/repo-a', + remoteName: 'origin', + remoteUrl: 'git@gh-personal:me/repo-a.git' + }) + expect(repos[0].repoIcon).toEqual({ + type: 'image', + source: 'github', + src: 'https://github.com/me.png?size=64', + label: 'me/repo-a' + }) + expect(repos[0].upstream).toBeUndefined() + + const setup = runtime.setupProjectExistingFolder({ + projectId: 'github:me/repo-a', + projectProviderIdentity: { provider: 'github', ...origin }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + await requiredStarted.promise + const completion = runtime.repositoryForkBackfill.resolve(repos[0]) + required.resolve({ + upstream: evidence === 'recovered parent' ? { owner: 'acme', repo: 'repo-a' } : undefined, + origin + }) + const result = await setup + await completion + expect(result.project.id).toBe('github:me/repo-a') + expect(result.repo.upstream).toEqual(evidence === 'recovered parent' ? origin : null) + parentProbe.mockResolvedValue({ upstream: { owner: 'acme', repo: 'repo-a' }, origin }) + await runtime.repositoryForkBackfill.run() + expect(repos[0].upstream).toEqual(evidence === 'recovered parent' ? origin : null) + expect( + projectHostSetupProjectionFromRepos(JSON.parse(JSON.stringify(repos))).setups[0].projectId + ).toBe('github:me/repo-a') + } finally { + ordinary.resolve({ upstream: undefined, origin }) + required.resolve({ upstream: undefined, origin }) + unsubscribe() + } + }) + } +) + +it('accepts remote-less saved-avatar equality without a required probe or new stamp', async () => { + await withGitFolder({}, async (path) => { + const repos: Repo[] = [ + { + id: 'legacy', + path: realpathSync(path), + displayName: 'repo-a', + badgeColor: 'blue', + addedAt: 1, + kind: 'git', + executionHostId: 'runtime:env-1', + repoIcon: { + type: 'image', + source: 'github', + src: 'https://github.com/me.png?size=64', + label: 'me/repo-a' + } + } + ] + const runtime = createRuntime(repos) + const background = Promise.withResolvers() + parentProbe.mockImplementationOnce(() => background.promise) + try { + const result = await runtime.setupProjectExistingFolder({ + projectId: 'github:me/repo-a', + projectProviderIdentity: { provider: 'github', owner: 'me', repo: 'repo-a' }, + hostId: 'runtime:env-1', + path, + kind: 'git' + }) + expect(result.project.id).toBe('github:me/repo-a') + expect(result.repo.upstream).toBeUndefined() + } finally { + const completion = runtime.repositoryForkBackfill.resolve(repos[0]) + background.resolve({ upstream: undefined, origin: null }) + await completion + } + expect(repos[0].upstream).toBeUndefined() + }) +}) diff --git a/src/main/runtime/orchestration/addressing/orchestration-caller-identity.ts b/src/main/runtime/orchestration/addressing/orchestration-caller-identity.ts index 5d5c12dd857..232428348e0 100644 --- a/src/main/runtime/orchestration/addressing/orchestration-caller-identity.ts +++ b/src/main/runtime/orchestration/addressing/orchestration-caller-identity.ts @@ -1,4 +1,5 @@ import type { RunRow } from '../db/orchestration-records' +import type { PeerRunRow } from '../db/peer-runs/peer-run-store' import { isEquivalentPaneKey } from '../db/pane-key-match' import { currentRunCoordinatorOrcaSessionId } from '../db/runs/run-coordinator-orca-session' import { @@ -16,6 +17,7 @@ export type OrchestrationCoordinatorKey = Pick< /** A caller the dispatch entry resolved from the Orca session id in its injected environment. */ export type OrchestrationSessionCaller = OrchestrationCallerIdentity & Readonly<{ + kind?: undefined orcaSessionId: OrcaSessionId /** The session record the request came from. */ sessionId: OrcaSessionId @@ -23,6 +25,50 @@ export type OrchestrationSessionCaller = OrchestrationCallerIdentity & workspaceId: string }> +/** A paired Orca acting as the coordinator of its Run here, as its authenticated frame names it. + * Its handle and binding key are its address, which no terminal or session here can have. */ +export type OrchestrationPeerCaller = OrchestrationCallerIdentity & + Readonly<{ + kind: 'peer' + terminalHandle: string + paneKey: string + orcaSessionId: null + peerRun: PeerRunRow + }> + +/** The caller the dispatch entry resolved, which wins over any declared handle: a session from + * its environment, or a paired Orca from its pairing. */ +export type OrchestrationEntryCaller = OrchestrationSessionCaller | OrchestrationPeerCaller + +/** The address, and Run binding key, of the paired Orca coordinating a conversation's Run here. */ +export function peerCoordinatorAddress(conversationId: string): string { + return `${PEER_ADDRESS_PREFIX}${conversationId}` +} + +const PEER_ADDRESS_PREFIX = 'peer:' + +export function isPeerCoordinatorAddress(value: string | null | undefined): boolean { + return !!value?.startsWith(PEER_ADDRESS_PREFIX) +} + +export function peerCoordinatorCaller(peerRun: PeerRunRow): OrchestrationPeerCaller { + const address = peerCoordinatorAddress(peerRun.conversation_id) + return Object.freeze({ + kind: 'peer', + address, + terminalHandle: address, + paneKey: address, + orcaSessionId: null, + peerRun + }) +} + +export function isPeerCaller( + caller: OrchestrationCallerIdentity | null | undefined +): caller is OrchestrationPeerCaller { + return !!caller && 'kind' in caller && caller.kind === 'peer' +} + /** A caller with neither a pane nor an Orca session id can never be bound to a Run. */ export function hasRunBindingKey(caller: OrchestrationCoordinatorKey): boolean { return caller.paneKey !== null || caller.orcaSessionId !== null diff --git a/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts b/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts index 7d5bc369062..68624a6ade3 100644 --- a/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts +++ b/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts @@ -11,6 +11,7 @@ import { attachFederationRelayAck } from './federation/federation-relay-ack' import { attachLegacyRemoteDbMethods } from '../legacy-remote/legacy-remote-db-methods' import { attachLegacyRemoteHomeDbMethods } from '../legacy-remote-home/legacy-remote-home-db-methods' import { attachPeerMailStore } from './federation/peer-mail-store' +import { attachPeerRunStore } from './peer-runs/peer-run-store' import { attachLegacyAskOperation } from './legacy/legacy-ask-operation' import { attachLegacyCompatibilityCandidates } from './legacy/legacy-compatibility-candidates' import { attachLegacyCompatibilityPrincipals } from './legacy/legacy-compatibility-principals' @@ -107,6 +108,7 @@ export function attachOrchestrationDbMethods(ctor: { prototype: object }): void attachLegacyRemoteDbMethods(ctor) attachFederationRelayAck(ctor) attachPeerMailStore(ctor) + attachPeerRunStore(ctor) attachWorkerTerminalResourceStore(ctor) attachWorkerTerminalTransfer(ctor) attachWorkerTerminalRelease(ctor) diff --git a/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts b/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts index 9152202ada9..4f812539964 100644 --- a/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts +++ b/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts @@ -168,6 +168,10 @@ export function settleWorkerReportInTransaction( let dispatchUpdate: { changes: number } let taskUpdate: { changes: number } if (settledByUnobservedPrompt) { + // A paired coordinator gets the correction once, after all its writes; see peer_run_corrections. + this.db + .prepare('INSERT INTO peer_run_corrections (dispatch_id) VALUES (?)') + .run(params.dispatchId) const now = new Date().toISOString() const dispatchTransition = transitionLifecycleWithDb(this.db, { entity: 'dispatch', @@ -239,6 +243,7 @@ export function settleWorkerReportInTransaction( projection: { stage: 'settled', updated_at: new Date().toISOString() }, correction: 'unobserved_prompt_report' }) + this.db.prepare('DELETE FROM peer_run_corrections WHERE dispatch_id = ?').run(params.dispatchId) } else if ((unprovenWorker || reportingStart) && params.outcome === 'succeeded') { transitionLifecycleWithDb(this.db, { entity: 'worker', 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 da829b40e5e..ffe1e3b2cb9 100644 --- a/src/main/runtime/orchestration/db/federation/peer-mail-store.ts +++ b/src/main/runtime/orchestration/db/federation/peer-mail-store.ts @@ -78,7 +78,7 @@ export function listHomePeerMailEnvironments(this: OrchestrationDb): string[] { export function listPeerConversationIds(this: OrchestrationDb, peerFingerprint: string): string[] { const statement = this.db.prepare( `SELECT conversation_id FROM peer_mail_conversations - WHERE role = 'peer' AND peer_fingerprint = ?` + WHERE role = 'peer' AND peer_fingerprint = ? ORDER BY conversation_id` ) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT over this table returns exactly these columns. const rows = statement.all(peerFingerprint) as { conversation_id: string }[] @@ -118,6 +118,14 @@ export function insertPeerMailMessage( | { message: MessageRow | undefined; duplicate: true } { this.db.exec('SAVEPOINT peer_mail_insert') try { + // A peer Run's conversation keeps its own queue sequence, so it never carries peer mail. + if (this.getPeerRunForConversation(params.conversationId)) { + throw new OrchestrationError( + 'request_mismatch', + `Conversation ${params.conversationId} belongs to a coordinated Run. Nothing was delivered.`, + { effectsApplied: false } + ) + } if (params.peerFingerprint !== undefined) { const conversation = this.getPeerMailConversation(params.conversationId) if ( diff --git a/src/main/runtime/orchestration/db/lifecycle-transition.ts b/src/main/runtime/orchestration/db/lifecycle-transition.ts index 5eefd879ecb..f0b44ee85ae 100644 --- a/src/main/runtime/orchestration/db/lifecycle-transition.ts +++ b/src/main/runtime/orchestration/db/lifecycle-transition.ts @@ -1,6 +1,7 @@ import type Database from '../../../sqlite/sync-database' import { OrchestrationError } from '../orchestration-error' import type { OrchestrationDb } from './orchestration-db' +import { notifyPeerMailQueued } from '../federation/peer-mail/peer-mail-waiters' /** Callers own transactions so lifecycle projections and mailbox effects commit atomically together. */ export type LifecycleEntity = 'task' | 'dispatch' | 'worker' @@ -189,7 +190,8 @@ export function transitionLifecycleWithDb( `${params.entity} ${params.id} changed while transitioning.` ) } - + // A peer Run's change is queued home by trigger in this statement. + notifyPeerMailQueued(db) return { changed: true } } diff --git a/src/main/runtime/orchestration/db/messages/message-inbox.ts b/src/main/runtime/orchestration/db/messages/message-inbox.ts index e0ec891fd63..f201d19e808 100644 --- a/src/main/runtime/orchestration/db/messages/message-inbox.ts +++ b/src/main/runtime/orchestration/db/messages/message-inbox.ts @@ -226,11 +226,14 @@ export function markAsReadAndDelivered(this: OrchestrationDb, ids: string[]): vo ) } -export function getInbox(this: OrchestrationDb, limit = 20): MessageRow[] { +export function getInbox(this: OrchestrationDb, limit = 20, runId?: string): MessageRow[] { 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 ORDER BY sequence DESC LIMIT ?') - .all(limit) as MessageRow[] + .prepare( + 'SELECT * FROM messages WHERE (?1 IS NULL OR run_id = ?1) ORDER BY sequence DESC LIMIT ?2' + ) + .all(runId ?? null, limit) as MessageRow[] ) } @@ -239,22 +242,19 @@ export function getAllMessagesForHandle( this: OrchestrationDb, toHandle: string, limit = 100, - types?: MessageType[] + types?: MessageType[], + runId?: string ): MessageRow[] { - if (types && types.length > 0) { - const placeholders = types.map(() => '?').join(',') - return exposeMessageListTimestamps( - this.db - .prepare( - `SELECT * FROM messages WHERE to_handle = ? AND type IN (${placeholders}) ORDER BY sequence DESC LIMIT ?` - ) - .all(toHandle, ...types, limit) as MessageRow[] - ) - } + const typed = types && types.length > 0 + const typeFilter = typed ? `AND type IN (${types.map(() => '?').join(',')})` : '' 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 = ? ORDER BY sequence DESC LIMIT ?') - .all(toHandle, limit) as MessageRow[] + .prepare( + `SELECT * FROM messages WHERE to_handle = ? AND (? IS NULL OR run_id = ?) ${typeFilter} + ORDER BY sequence DESC LIMIT ?` + ) + .all(toHandle, runId ?? null, runId ?? null, ...(typed ? types : []), limit) as MessageRow[] ) } diff --git a/src/main/runtime/orchestration/db/messages/message-insert.ts b/src/main/runtime/orchestration/db/messages/message-insert.ts index cc590b76b1a..24c45a19e7d 100644 --- a/src/main/runtime/orchestration/db/messages/message-insert.ts +++ b/src/main/runtime/orchestration/db/messages/message-insert.ts @@ -8,6 +8,7 @@ import { generateId } from '../generated-id' import { exposeMessageTimestamps } from '../utc-timestamp' import type { OrchestrationDb } from '../orchestration-db' import { runLifecycleWriteTransaction } from '../lifecycle-write-transaction-runner' +import { notifyPeerMailQueued } from '../../federation/peer-mail/peer-mail-waiters' import { ORCHESTRATION_UNBOUND_RUN_ID as UNBOUND_RUN_ID } from '../../../../../shared/orchestration/orchestration-rpc-contract' const MESSAGE_INSERT_SAVEPOINT = 'message_insert_batch' @@ -27,6 +28,8 @@ export type MessageInsert = { runId?: string answerSenderSnapshot?: string deliveryContract?: MessageDeliveryContract + /** The Dispatch whose worker sent this, as the sender's own check found it; kept for a peer Run's queue. */ + senderDispatchId?: string } export function insertMessage(this: OrchestrationDb, msg: MessageInsert): MessageRow { @@ -44,6 +47,16 @@ export function insertMessage(this: OrchestrationDb, msg: MessageInsert): Messag this.requireRun(runId) const id = msg.id ?? generateId('msg') const type = msg.type ?? 'status' + if (msg.senderDispatchId) { + // Before the insert, whose trigger queues a peer Run's mail home with it; immutable after. + this.db + .prepare( + `INSERT OR IGNORE INTO message_dispatch_provenance (message_id, dispatch_id, task_id) + SELECT ?, d.id, d.task_id FROM dispatch_contexts d + WHERE d.id = ? AND d.run_id IN (SELECT run_id FROM peer_runs)` + ) + .run(id, msg.senderDispatchId) + } // Heartbeats only record liveness: store them handled so they never reach a mailbox or wake it. const handled = type === 'heartbeat' ? 1 : 0 const stmt = this.db.prepare(` @@ -70,6 +83,8 @@ export function insertMessage(this: OrchestrationDb, msg: MessageInsert): Messag handled, handled ) + // Mail filed in a peer Run is queued home by trigger in this statement. + notifyPeerMailQueued(this.db) return exposeMessageTimestamps( this.db.prepare('SELECT * FROM messages WHERE id = ?').get(id) as MessageRow ) diff --git a/src/main/runtime/orchestration/db/orchestration-db-methods.ts b/src/main/runtime/orchestration/db/orchestration-db-methods.ts index 0e06a05191d..9072fe5c5fe 100644 --- a/src/main/runtime/orchestration/db/orchestration-db-methods.ts +++ b/src/main/runtime/orchestration/db/orchestration-db-methods.ts @@ -10,6 +10,7 @@ import type { FederationRelayAckMethods } from './federation/federation-relay-ac import type { LegacyRemoteDbMethods } from '../legacy-remote/legacy-remote-db-methods' import type { LegacyRemoteHomeDbMethods } from '../legacy-remote-home/legacy-remote-home-db-methods' import type { PeerMailStoreMethods } from './federation/peer-mail-store' +import type { PeerRunStoreMethods } from './peer-runs/peer-run-store' import type { LegacyAskOperationMethods } from './legacy/legacy-ask-operation' import type { LegacyCompatibilityCandidatesMethods } from './legacy/legacy-compatibility-candidates' import type { LegacyCompatibilityPrincipalsMethods } from './legacy/legacy-compatibility-principals' @@ -104,6 +105,7 @@ export type OrchestrationDbMethods = AttemptObservationStoreMethods & LegacyRemoteDbMethods & FederationRelayAckMethods & PeerMailStoreMethods & + PeerRunStoreMethods & StructuredMailSendStoreMethods & WorkerTerminalResourceStoreMethods & WorkerTerminalTransferMethods & diff --git a/src/main/runtime/orchestration/db/orchestration-db.ts b/src/main/runtime/orchestration/db/orchestration-db.ts index 25bec3ae31c..3fcd88f18b1 100644 --- a/src/main/runtime/orchestration/db/orchestration-db.ts +++ b/src/main/runtime/orchestration/db/orchestration-db.ts @@ -15,6 +15,7 @@ import { rememberCurrentRunCoordinatorHandles } from './runs/run-coordinator-mail-routing' import { createTables } from './schema/create-tables' +import { createPeerRunQueueTriggers } from './peer-runs/peer-run-queue-sql' import { migrate } from './schema/migrate' import { backfillStructuredWorkerOrcaSessionIds } from './schema/structured-worker-orca-session-backfill' import { reconcileSettledWorkerDispatches } from './worker-dispatch/worker-dispatch-settlement' @@ -63,6 +64,7 @@ class OrchestrationDbCore { } } createRunCoordinatorAddressTriggers(this.db) + createPeerRunQueueTriggers(this.db) backfillFederatedStubHomeRuns(this.db) // After every open step that creates Runs, before any step that deletes work. installRemovedWorkCapture(this.db, removedWorkCaptureWasIntact) diff --git a/src/main/runtime/orchestration/db/peer-runs/peer-run-queue-sql.ts b/src/main/runtime/orchestration/db/peer-runs/peer-run-queue-sql.ts new file mode 100644 index 00000000000..c2862a64508 --- /dev/null +++ b/src/main/runtime/orchestration/db/peer-runs/peer-run-queue-sql.ts @@ -0,0 +1,175 @@ +import type Database from '../../../../sqlite/sync-database' +import { REMOTE_OWNED_WIRE_VERSION } from '../../../../../shared/orchestration/remote-owned-wire' + +/** + * A Run here whose coordinator is a paired Orca, keyed by the conversation its queue goes home + * under. It outlives this Orca's resets, so the conversation keeps its Run ID and its sequence. + * Each conversation's next `to_home` sequence is persistent too, so a reset never reuses one. + * A worker message's Dispatch is recorded when it is filed, before any reroute into the Run. + */ +export const PEER_RUN_SCHEMA_SQL = ` +CREATE TABLE IF NOT EXISTS peer_runs ( + run_id TEXT PRIMARY KEY, + conversation_id TEXT NOT NULL UNIQUE, + peer_fingerprint TEXT NOT NULL, + home_run_id TEXT NOT NULL, + home_label TEXT NOT NULL, + state TEXT NOT NULL DEFAULT 'open' CHECK(state IN ('open', 'closed')), + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +CREATE TABLE IF NOT EXISTS federation_relay_sequences ( + dispatch_id TEXT NOT NULL, + direction TEXT NOT NULL, + last_sequence INTEGER NOT NULL, + PRIMARY KEY (dispatch_id, direction) +); + +-- A Dispatch whose report owner's correction is being written: its edges queue nothing until the +-- row is removed, which queues the corrected state once, flagged. +CREATE TABLE IF NOT EXISTS peer_run_corrections ( + dispatch_id TEXT PRIMARY KEY +); + +CREATE TABLE IF NOT EXISTS message_dispatch_provenance ( + message_id TEXT PRIMARY KEY, + dispatch_id TEXT NOT NULL, + task_id TEXT NOT NULL +); +` + +/** A peer-Run Dispatch as a `worker_state` item carries it, with its Task and Run. */ +const PEER_RUN_DISPATCH_STATE_VIEW_SQL = ` +DROP VIEW IF EXISTS peer_run_dispatch_state; +CREATE VIEW peer_run_dispatch_state AS +SELECT d.id AS dispatch_id, pr.conversation_id, pr.home_run_id, pr.run_id AS peer_run_id, + json_object( + 'id', d.id, 'taskId', d.task_id, 'status', d.status, 'workerState', w.state, + 'lastFailure', d.last_failure, 'agent', json_extract(w.start_options, '$.agent') + ) AS dispatch_json, + json_object('status', t.status, 'result', t.result) AS task_json +FROM dispatch_contexts d +JOIN peer_runs pr ON pr.run_id = d.run_id +JOIN tasks t ON t.id = d.task_id +LEFT JOIN worker_dispatches w ON w.dispatch_id = d.id; +` + +const SEQUENCE = `(SELECT last_sequence FROM federation_relay_sequences + WHERE dispatch_id = conversation_id AND direction = 'to_home')` + +/** + * Takes the conversation's next sequence, then queues the item under it. `rows` selects at most one + * row with `conversation_id` and the item's `message_id` and `payload`; both statements read it. + */ +function queueItemStatements(rows: string, kind: string): [string, string] { + return [ + `INSERT INTO federation_relay_sequences (dispatch_id, direction, last_sequence) + SELECT conversation_id, 'to_home', 1 FROM (${rows}) WHERE true + ON CONFLICT(dispatch_id, direction) DO UPDATE SET last_sequence = last_sequence + 1`, + `INSERT INTO federation_relay_items + (dispatch_id, direction, sequence, message_id, kind, payload, byte_count) + SELECT conversation_id, 'to_home', ${SEQUENCE}, message_id, '${kind}', payload, length(payload) + FROM (${rows})` + ] +} + +/** One `worker_state` item for a peer-Run Dispatch; its ID is the sequence it is queued under. */ +export function peerRunDispatchStateStatements( + dispatchId: string, + corrected: boolean, + removed: string +): [string, string] { + return queueItemStatements( + `SELECT conversation_id, 'state_' || ${SEQUENCE} AS message_id, + json_object( + 'v', ${REMOTE_OWNED_WIRE_VERSION}, 'id', 'state_' || ${SEQUENCE}, + 'homeRunId', home_run_id, 'peerRunId', peer_run_id, + 'dispatch', json(dispatch_json), 'task', json(task_json), + 'correctedUnobservedPrompt', json('${corrected}'), + 'removed', ${removed} + ) AS payload + FROM peer_run_dispatch_state WHERE dispatch_id = ${dispatchId}`, + 'worker_state' + ) +} + +/** A message filed in a peer Run's mailbox, once, with the Dispatch its sender worked for. */ +function peerRunMailStatements(row: string): [string, string] { + return queueItemStatements( + `SELECT pr.conversation_id, ${row}.id AS message_id, + json_object( + 'v', ${REMOTE_OWNED_WIRE_VERSION}, 'id', ${row}.id, + 'homeRunId', pr.home_run_id, 'peerRunId', pr.run_id, + 'message', json_object( + 'from', ${row}.from_handle, 'type', ${row}.type, 'subject', ${row}.subject, + 'body', ${row}.body, 'payload', ${row}.payload, 'priority', ${row}.priority, + 'threadId', ${row}.thread_id + ), + 'dispatchId', p.dispatch_id, 'taskId', p.task_id + ) AS payload + FROM peer_runs pr + LEFT JOIN message_dispatch_provenance p ON p.message_id = ${row}.id + WHERE ${row}.to_handle = 'run:' || pr.run_id + AND NOT EXISTS ( + SELECT 1 FROM federation_relay_items + WHERE dispatch_id = pr.conversation_id AND direction = 'to_home' + AND message_id = ${row}.id + )`, + 'worker_mail' + ) +} + +const LATEST_TASK_DISPATCH = (taskId: string) => + `(SELECT id FROM dispatch_contexts WHERE task_id = ${taskId} ORDER BY rowid DESC LIMIT 1)` + +const NOT_CORRECTING = (dispatchId: string) => + `NOT EXISTS (SELECT 1 FROM peer_run_corrections WHERE dispatch_id = ${dispatchId})` + +const trigger = (statements: [string, string]) => `BEGIN ${statements.join(';\n')}; END;` + +/** + * Every final message of a peer Run's mailbox and every lifecycle change of its Dispatches, their + * workers and their Tasks queue home in the transaction that made them. Rebuilt on every open. + * The report owner's unobserved-prompt correction queues once, flagged, after all its writes. + */ +export function createPeerRunQueueTriggers(db: Database.Database): void { + db.exec('BEGIN IMMEDIATE') + try { + db.exec(` + ${PEER_RUN_DISPATCH_STATE_VIEW_SQL} + DROP TRIGGER IF EXISTS trg_peer_run_mail_insert; + DROP TRIGGER IF EXISTS trg_peer_run_mail_reroute; + DROP TRIGGER IF EXISTS trg_peer_run_dispatch_insert; + DROP TRIGGER IF EXISTS trg_peer_run_dispatch_status; + DROP TRIGGER IF EXISTS trg_peer_run_worker_state; + DROP TRIGGER IF EXISTS trg_peer_run_task_status; + DROP TRIGGER IF EXISTS trg_peer_run_correction; + CREATE TRIGGER trg_peer_run_mail_insert AFTER INSERT ON messages + WHEN NEW.to_handle LIKE 'run:%' AND NEW.type <> 'heartbeat' + ${trigger(peerRunMailStatements('NEW'))} + CREATE TRIGGER trg_peer_run_mail_reroute AFTER UPDATE OF to_handle ON messages + WHEN NEW.to_handle LIKE 'run:%' AND NEW.to_handle <> OLD.to_handle AND NEW.type <> 'heartbeat' + ${trigger(peerRunMailStatements('NEW'))} + CREATE TRIGGER trg_peer_run_dispatch_insert AFTER INSERT ON dispatch_contexts + ${trigger(peerRunDispatchStateStatements('NEW.id', false, 'NULL'))} + CREATE TRIGGER trg_peer_run_dispatch_status AFTER UPDATE OF status ON dispatch_contexts + WHEN NEW.status <> OLD.status AND ${NOT_CORRECTING('NEW.id')} + ${trigger(peerRunDispatchStateStatements('NEW.id', false, 'NULL'))} + CREATE TRIGGER trg_peer_run_worker_state AFTER UPDATE OF state ON worker_dispatches + WHEN NEW.state <> OLD.state AND ${NOT_CORRECTING('NEW.dispatch_id')} + ${trigger(peerRunDispatchStateStatements('NEW.dispatch_id', false, 'NULL'))} + CREATE TRIGGER trg_peer_run_task_status AFTER UPDATE OF status ON tasks + WHEN NEW.status <> OLD.status AND NOT EXISTS ( + SELECT 1 FROM peer_run_corrections c JOIN dispatch_contexts d ON d.id = c.dispatch_id + WHERE d.task_id = NEW.id + ) + ${trigger(peerRunDispatchStateStatements(LATEST_TASK_DISPATCH('NEW.id'), false, 'NULL'))} + CREATE TRIGGER trg_peer_run_correction AFTER DELETE ON peer_run_corrections + ${trigger(peerRunDispatchStateStatements('OLD.dispatch_id', true, 'NULL'))} + `) + db.exec('COMMIT') + } catch (error) { + db.exec('ROLLBACK') + throw error + } +} diff --git a/src/main/runtime/orchestration/db/peer-runs/peer-run-queue.test.ts b/src/main/runtime/orchestration/db/peer-runs/peer-run-queue.test.ts new file mode 100644 index 00000000000..a8b9bd4ce3b --- /dev/null +++ b/src/main/runtime/orchestration/db/peer-runs/peer-run-queue.test.ts @@ -0,0 +1,265 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { OrchestrationDb } from '../orchestration-db' +import { generateId } from '../generated-id' +import { + RemoteOwnedWorkerMail, + RemoteOwnedWorkerState +} from '../../../../../shared/orchestration/remote-owned-wire' +import { AGENT_PROMPT_STALLED_ERROR } from '../../../terminal/input/agent-prompt-submission-verification' +import type { PeerRunRow } from './peer-run-store' + +describe("a paired Orca's Run: its queue home", () => { + let db: OrchestrationDb + let peerRun: PeerRunRow + + beforeEach(() => { + db = new OrchestrationDb(':memory:') + peerRun = db.admitPeerRun({ + peerFingerprint: 'fingerprint_a', + peerRun: { runId: 'run_home', conversationId: generateId('peerconv'), label: 'devA' } + }) + }) + + afterEach(() => db.close()) + + function start(params: { adoptTaskId?: string; retryOf?: string } = {}) { + return db.createStartingWorkerDispatch({ + taskSpec: 'Build it', + taskRunId: peerRun.run_id, + startOptions: { agent: 'claude' }, + creator: { kind: 'system' }, + maxDepth: 5, + ...params + }) + } + + function pending() { + return db.listPendingFederationRelay(peerRun.conversation_id, 'to_home', 500) + } + + function states() { + return pending() + .filter((item) => item.kind === 'worker_state') + .map((item) => RemoteOwnedWorkerState.parse(JSON.parse(item.payload))) + } + + function fail(dispatchId: string, taskId: string) { + db.transitionLifecycle({ entity: 'worker', id: dispatchId, from: 'starting', to: 'failed' }) + db.transitionLifecycle({ entity: 'dispatch', id: dispatchId, from: 'pending', to: 'failed' }) + db.transitionLifecycle({ entity: 'task', id: taskId, from: 'dispatched', to: 'failed' }) + } + + it('queues every lifecycle change of a Dispatch and its Task, in order, as the wire schema', () => { + const { dispatch, task } = start({ adoptTaskId: 'task_home1' }) + fail(dispatch.id, task.id) + + expect(task.id).toBe('task_home1') + const items = pending() + expect(items.map((item) => item.sequence)).toEqual(items.map((_, index) => index + 1)) + expect( + states().map((state) => [ + state.dispatch.status, + state.dispatch.workerState, + state.task.status + ]) + ).toEqual([ + ['pending', null, 'ready'], + ['pending', 'starting', 'dispatched'], + ['pending', 'failed', 'dispatched'], + ['failed', 'failed', 'dispatched'], + ['failed', 'failed', 'failed'] + ]) + expect(states().every((state) => state.homeRunId === 'run_home')).toBe(true) + for (const item of items) { + expect(JSON.parse(item.payload).id).toBe(item.message_id) + } + }) + + it("queues the report owner's unobserved-prompt correction once, flagged, with its result", () => { + const { dispatch, task } = start() + fail(dispatch.id, task.id) + db.transitionLifecycle({ + entity: 'dispatch', + id: dispatch.id, + from: 'failed', + to: 'failed', + projection: { last_failure: AGENT_PROMPT_STALLED_ERROR } + }) + const before = states().length + + db.settleWorkerReport({ + taskId: task.id, + dispatchId: dispatch.id, + outcome: 'succeeded', + result: 'actually done' + }) + + expect(states().slice(before)).toEqual([ + expect.objectContaining({ + correctedUnobservedPrompt: true, + dispatch: expect.objectContaining({ status: 'completed', workerState: 'succeeded' }), + task: { status: 'completed', result: 'actually done' } + }) + ]) + }) + + it('holds back the Task change of a correction even when a newer attempt is the latest', () => { + const first = start() + fail(first.dispatch.id, first.task.id) + db.transitionLifecycle({ + entity: 'dispatch', + id: first.dispatch.id, + from: 'failed', + to: 'failed', + projection: { last_failure: AGENT_PROMPT_STALLED_ERROR } + }) + const retry = start({ adoptTaskId: first.task.id }) + fail(retry.dispatch.id, first.task.id) + const before = states().length + + db.settleWorkerReport({ + taskId: first.task.id, + dispatchId: first.dispatch.id, + outcome: 'succeeded', + result: 'actually done' + }) + + expect(states().slice(before)).toEqual([ + expect.objectContaining({ + correctedUnobservedPrompt: true, + dispatch: expect.objectContaining({ id: first.dispatch.id }) + }) + ]) + }) + + it("queues a worker's question with its thread, so the coordinator can answer in it", () => { + const { dispatch } = start() + const { message } = db.createQuestion({ + runId: peerRun.run_id, + dispatchId: dispatch.id, + askerHandle: 'term_w', + question: 'Which branch?' + }) + const queued = pending().find((item) => item.message_id === message.id)! + expect(RemoteOwnedWorkerMail.parse(JSON.parse(queued.payload)).message.threadId).toBe( + message.id + ) + }) + + it('never reuses a sequence after a reset, and a reset tells the coordinator what it removed', () => { + const first = start() + const throughOld = Math.max(...pending().map((item) => item.sequence)) + + db.resetTasks() + const removed = states().filter((state) => state.removed) + expect(removed.map((state) => [state.dispatch.id, state.removed?.reason])).toEqual([ + [first.dispatch.id, 'reset on the server running it'] + ]) + start() + db.acknowledgeFederationRelay({ + dispatchId: peerRun.conversation_id, + direction: 'to_home', + throughSequence: throughOld + }) + + const after = pending() + expect(after.length).toBeGreaterThan(0) + expect(after.every((item) => item.sequence > throughOld)).toBe(true) + }) + + it('keeps the queue and the Run ID through a full reset, with a removed item per Dispatch', () => { + const { dispatch } = start() + db.resetAll() + + expect(states().find((state) => state.removed)?.dispatch.id).toBe(dispatch.id) + const again = db.admitPeerRun({ + peerFingerprint: 'fingerprint_a', + peerRun: { runId: 'run_home', conversationId: peerRun.conversation_id, label: 'devA' } + }) + expect(again.run_id).toBe(peerRun.run_id) + expect(db.getRun(peerRun.run_id)).toBeDefined() + }) + + it('attributes mail rerouted into the Run to the Dispatch its sender worked for when it sent it', () => { + const coordinator = `peer:${peerRun.conversation_id}` + const first = start() + const note = db.insertMessage({ + from: 'term_w', + to: 'term_unbound', + subject: 'late note', + runId: peerRun.run_id, + senderDispatchId: first.dispatch.id + }) + fail(first.dispatch.id, first.task.id) + start() + db.db.prepare('UPDATE messages SET to_handle = ? WHERE id = ?').run(coordinator, note.id) + db.db + .prepare('UPDATE messages SET to_handle = ? WHERE id = ?') + .run(`run:${peerRun.run_id}`, note.id) + + const mail = pending() + .filter((item) => item.kind === 'worker_mail') + .map((item) => RemoteOwnedWorkerMail.parse(JSON.parse(item.payload))) + expect(mail.map((item) => [item.id, item.dispatchId, item.taskId])).toEqual([ + [note.id, first.dispatch.id, first.task.id] + ]) + }) + + it('reopens an adopted Task whose last attempt settled, so the coordinator can run it again', () => { + const first = start({ adoptTaskId: 'task_home1' }) + fail(first.dispatch.id, first.task.id) + + const again = start({ adoptTaskId: 'task_home1' }) + expect(again.task.id).toBe('task_home1') + expect(again.dispatch.id).not.toBe(first.dispatch.id) + expect(() => start({ adoptTaskId: 'task_home1' })).toThrow(/only a ready Task can start/) + }) + + it('keeps a peer Run conversation and a peer-mail conversation apart, so their sequences never collide', () => { + const mailConversation = generateId('peerconv') + db.insertPeerMailMessage({ + conversationId: mailConversation, + peerFingerprint: 'fingerprint_a', + remoteParty: null, + message: { id: generateId('msg'), from: 'devA:term_x', to: 'term_w', subject: 'hi' } + }) + expect(() => + db.admitPeerRun({ + peerFingerprint: 'fingerprint_a', + peerRun: { runId: 'run_home2', conversationId: mailConversation, label: 'devA' } + }) + ).toThrow(expect.objectContaining({ code: 'request_mismatch' })) + expect(() => + db.insertPeerMailMessage({ + conversationId: peerRun.conversation_id, + peerFingerprint: 'fingerprint_a', + remoteParty: null, + message: { id: generateId('msg'), from: 'devA:term_x', to: 'term_w', subject: 'hi' } + }) + ).toThrow(expect.objectContaining({ code: 'request_mismatch' })) + }) + + it("follows a rename of the coordinating Orca's machine", () => { + const renamed = db.admitPeerRun({ + peerFingerprint: 'fingerprint_a', + peerRun: { runId: 'run_home', conversationId: peerRun.conversation_id, label: 'devA2' } + }) + expect(renamed.home_label).toBe('devA2') + }) + + it('leaves an adopted Task that still waits on its dependencies waiting', () => { + const dependency = db.createTask({ spec: 'first', runId: peerRun.run_id }) + const task = db.createTask({ + spec: 'second', + runId: peerRun.run_id, + deps: [dependency.id] + }) + expect(() => start({ adoptTaskId: task.id })).toThrow(/only a ready Task can start/) + expect(db.getTask(task.id)?.status).toBe('pending') + }) + + it('admits no start into a Run its coordinator cancelled', () => { + db.closePeerRun(peerRun.run_id) + expect(() => start()).toThrow(/cancelled by devA/) + }) +}) diff --git a/src/main/runtime/orchestration/db/peer-runs/peer-run-store.ts b/src/main/runtime/orchestration/db/peer-runs/peer-run-store.ts new file mode 100644 index 00000000000..20f70500176 --- /dev/null +++ b/src/main/runtime/orchestration/db/peer-runs/peer-run-store.ts @@ -0,0 +1,146 @@ +import type { RemoteOwnedPeerRun } from '../../../../../shared/orchestration/remote-owned-wire' +import { OrchestrationError } from '../../orchestration-error' +import { generateId } from '../generated-id' +import type { OrchestrationDb } from '../orchestration-db' +import { peerRunDispatchStateStatements } from './peer-run-queue-sql' +import { peerCoordinatorAddress } from '../../addressing/orchestration-caller-identity' + +export type PeerRunRow = { + run_id: string + conversation_id: string + peer_fingerprint: string + home_run_id: string + home_label: string + state: 'open' | 'closed' + created_at: string +} + +const NO_EFFECTS = { effectsApplied: false } as const + +/** + * The Run a paired Orca coordinates here for one conversation, written when its frame arrives and + * before any await, so a later frame of the same conversation (a cancel) always finds it. The Run + * keeps its ID across this Orca's resets: a reset that removed its row gets it back on the next call. + */ +export function admitPeerRun( + this: OrchestrationDb, + params: { peerFingerprint: string; peerRun: RemoteOwnedPeerRun } +): PeerRunRow { + const { peerFingerprint, peerRun } = params + this.db.exec('BEGIN IMMEDIATE') + try { + const conversation = this.getPeerMailConversation(peerRun.conversationId) + const existing = this.getPeerRunForConversation(peerRun.conversationId) + // A peer-mail conversation keeps its own queue sequence, so it never becomes a peer Run's. + if ( + existing + ? existing.peer_fingerprint !== peerFingerprint || existing.home_run_id !== peerRun.runId + : conversation + ) { + throw new OrchestrationError( + 'request_mismatch', + `Conversation ${peerRun.conversationId} belongs to another Run or pairing. No effects were applied.`, + NO_EFFECTS + ) + } + const runId = existing?.run_id ?? generateId('run') + if (existing && existing.home_label !== peerRun.label) { + this.db + .prepare('UPDATE peer_runs SET home_label = ? WHERE run_id = ?') + .run(peerRun.label, runId) + } + if (!existing) { + this.db + .prepare( + `INSERT OR IGNORE INTO peer_mail_conversations (conversation_id, role, peer_fingerprint) + VALUES (?, 'peer', ?)` + ) + .run(peerRun.conversationId, peerFingerprint) + this.db + .prepare( + `INSERT INTO peer_runs (run_id, conversation_id, peer_fingerprint, home_run_id, home_label) + VALUES (?, ?, ?, ?, ?)` + ) + .run(runId, peerRun.conversationId, peerFingerprint, peerRun.runId, peerRun.label) + } + if (!this.getRunRaw(runId)) { + const coordinator = peerCoordinatorAddress(peerRun.conversationId) + this.insertRunRow(runId, { + objective: `Coordinated from ${peerRun.label}`, + coordinatorHandle: coordinator, + coordinatorPaneKey: coordinator + }) + } + this.db.exec('COMMIT') + } catch (error) { + this.db.exec('ROLLBACK') + throw error + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the committed transaction above wrote or found this conversation's row. + return this.getPeerRunForConversation(peerRun.conversationId) as PeerRunRow +} + +export function getPeerRun(this: OrchestrationDb, runId: string): PeerRunRow | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over this table returns exactly its row shape. + return this.db.prepare('SELECT * FROM peer_runs WHERE run_id = ?').get(runId) as + | PeerRunRow + | undefined +} + +export function hasPeerRuns(this: OrchestrationDb): boolean { + return this.db.prepare('SELECT 1 FROM peer_runs LIMIT 1').get() !== undefined +} + +export function getPeerRunForConversation( + this: OrchestrationDb, + conversationId: string +): PeerRunRow | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over this table returns exactly its row shape. + return this.db + .prepare('SELECT * FROM peer_runs WHERE conversation_id = ?') + .get(conversationId) as PeerRunRow | undefined +} + +/** Closed for good: the claim refuses every start, follow-up and helper into it from now on. */ +export function closePeerRun(this: OrchestrationDb, runId: string): void { + this.db.prepare(`UPDATE peer_runs SET state = 'closed' WHERE run_id = ?`).run(runId) +} + +/** Inside a reset's transaction, before it deletes them: one final item per peer-Run Dispatch. */ +export function queueRemovedPeerRunDispatches(this: OrchestrationDb, reason: string): void { + const [allocate, queue] = peerRunDispatchStateStatements( + '?1', + false, + `json_object('reason', ?2)` + ).map((sql) => this.db.prepare(sql)) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT of one column returns exactly that column. + const dispatches = this.db + .prepare( + `SELECT d.id FROM dispatch_contexts d JOIN peer_runs pr ON pr.run_id = d.run_id ORDER BY d.rowid` + ) + .all() as { id: string }[] + for (const { id } of dispatches) { + allocate.run(id, reason) + queue.run(id, reason) + } +} + +export type PeerRunStoreMethods = { + admitPeerRun: typeof admitPeerRun + getPeerRun: typeof getPeerRun + getPeerRunForConversation: typeof getPeerRunForConversation + hasPeerRuns: typeof hasPeerRuns + closePeerRun: typeof closePeerRun + queueRemovedPeerRunDispatches: typeof queueRemovedPeerRunDispatches +} + +export function attachPeerRunStore(ctor: { prototype: object }): void { + Object.assign(ctor.prototype, { + admitPeerRun, + getPeerRun, + getPeerRunForConversation, + hasPeerRuns, + closePeerRun, + queueRemovedPeerRunDispatches + }) +} diff --git a/src/main/runtime/orchestration/db/questions/question-threads.ts b/src/main/runtime/orchestration/db/questions/question-threads.ts index 4f0be287206..5741dc5750a 100644 --- a/src/main/runtime/orchestration/db/questions/question-threads.ts +++ b/src/main/runtime/orchestration/db/questions/question-threads.ts @@ -2,6 +2,7 @@ import type { MessageRow, QuestionRow } from '../orchestration-records' import { OrchestrationError } from '../../orchestration-error' import { exposeQuestionTimestamps } from '../utc-timestamp' import type { OrchestrationDb } from '../orchestration-db' +import { generateId } from '../generated-id' import { handHelperMailToRun } from '../messages/helper-mailbox-hand-back' export function createQuestion( @@ -27,7 +28,11 @@ export function createQuestion( `Dispatch ${params.dispatchId} is not in Run ${params.runId}.` ) } + // A question is its own thread, set at insert so mail queued for a paired coordinator carries it. + const id = generateId('msg') const message = this.insertMessage({ + id, + threadId: id, from: `dispatch:${params.dispatchId}`, to: params.to ?? `run:${params.runId}`, subject: 'Question', @@ -39,9 +44,9 @@ export function createQuestion( question: params.question, options: params.options ?? [] }), + senderDispatchId: dispatch.id, runId: params.runId }) - this.db.prepare('UPDATE messages SET thread_id = ? WHERE id = ?').run(message.id, message.id) this.db .prepare( `INSERT INTO question_threads ( diff --git a/src/main/runtime/orchestration/db/reset/orchestration-reset.ts b/src/main/runtime/orchestration/db/reset/orchestration-reset.ts index ac68ba65767..b8af86962be 100644 --- a/src/main/runtime/orchestration/db/reset/orchestration-reset.ts +++ b/src/main/runtime/orchestration/db/reset/orchestration-reset.ts @@ -1,5 +1,6 @@ import { ORCHESTRATION_LEGACY_RUN_ID as LEGACY_RUN_ID } from '../../../../../shared/orchestration/orchestration-rpc-contract' import type { OrchestrationDb } from '../orchestration-db' +import { notifyPeerMailQueued } from '../../federation/peer-mail/peer-mail-waiters' import type { ResetRemovedWork } from '../../../../../shared/orchestration/orchestration-removed-work' import { readRemovedWorkWatermark, @@ -7,13 +8,22 @@ import { } from './removed-orchestration-work-read' /** Returns the removed-work watermark, read inside the transaction so the reply counts only this reset. */ -export function runResetTransaction(this: OrchestrationDb, statements: string): number { +export function runResetTransaction( + this: OrchestrationDb, + statements: string, + { removesDispatches = false }: { removesDispatches?: boolean } = {} +): number { this.db.exec('BEGIN IMMEDIATE') try { // Why unguarded: an error that ends the transaction must roll the whole reset back, not let the deletes autocommit. const watermark = readRemovedWorkWatermark(this.db) + if (removesDispatches) { + // Their paired coordinator learns of it from its queue, which the reset keeps. + this.queueRemovedPeerRunDispatches('reset on the server running it') + } this.db.exec(statements) this.db.exec('COMMIT') + notifyPeerMailQueued(this.db) return watermark } catch (error) { try { @@ -27,7 +37,8 @@ export function runResetTransaction(this: OrchestrationDb, statements: string): export function resetAll(this: OrchestrationDb): void { // Keep receipts so a lost reset reply cannot replay the mutation. - this.runResetTransaction(` + this.runResetTransaction( + ` DELETE FROM coordinator_runs; DELETE FROM decision_gates; DELETE FROM remote_questions; @@ -37,7 +48,7 @@ export function resetAll(this: OrchestrationDb): void { DELETE FROM legacy_operation_receipts; DELETE FROM legacy_compatibility_principals; DELETE FROM legacy_adoptions; - DELETE FROM federation_relay_items; + DELETE FROM federation_relay_items WHERE NOT (direction = 'to_home' AND dispatch_id IN (SELECT conversation_id FROM peer_runs)); DELETE FROM remote_dispatch_attachments; DELETE FROM federated_dispatches; DELETE FROM worker_terminal_archives; @@ -48,18 +59,22 @@ export function resetAll(this: OrchestrationDb): void { DELETE FROM dispatch_contexts; DELETE FROM tasks; DELETE FROM messages; + DELETE FROM message_dispatch_provenance; DELETE FROM run_coordinator_handles; DELETE FROM runs; DELETE FROM removed_orchestration_work; INSERT INTO runs (id, objective, home_database, consumer_generation, legacy) VALUES ('${LEGACY_RUN_ID}', 'Legacy orchestration state (inspect only)', 'this_database', 0, 1); - `) + `, + { removesDispatches: true } + ) this.hasAnyDispatchContextsCache = undefined } export function resetTasks(this: OrchestrationDb): ResetRemovedWork | undefined { // Messages survive, and so do replies waiting for a paired Orca to pull them; close threads so orphaned questions cannot masquerade as generic replies. - const watermark = this.runResetTransaction(` + const watermark = this.runResetTransaction( + ` DELETE FROM coordinator_runs; DELETE FROM decision_gates; DELETE FROM remote_questions; @@ -70,7 +85,7 @@ export function resetTasks(this: OrchestrationDb): ResetRemovedWork | undefined DELETE FROM legacy_operation_receipts; DELETE FROM legacy_compatibility_principals; DELETE FROM legacy_adoptions; - DELETE FROM federation_relay_items WHERE kind <> 'peer_mail'; + DELETE FROM federation_relay_items WHERE kind <> 'peer_mail' AND NOT (direction = 'to_home' AND dispatch_id IN (SELECT conversation_id FROM peer_runs)); DELETE FROM remote_dispatch_attachments; DELETE FROM federated_dispatches; DELETE FROM worker_terminal_archives; @@ -80,7 +95,9 @@ export function resetTasks(this: OrchestrationDb): ResetRemovedWork | undefined DELETE FROM worker_dispatches; DELETE FROM dispatch_contexts; DELETE FROM tasks; - `) + `, + { removesDispatches: true } + ) this.hasAnyDispatchContextsCache = undefined return summarizeRemovedWorkSince(this.db, watermark) } @@ -92,6 +109,7 @@ export function resetMessages(this: OrchestrationDb): void { DELETE FROM question_threads; DELETE FROM deliveries; DELETE FROM messages; + DELETE FROM message_dispatch_provenance; DELETE FROM structured_pointer_operations; `) } diff --git a/src/main/runtime/orchestration/db/runs/run-binding.ts b/src/main/runtime/orchestration/db/runs/run-binding.ts index 0d47fd2e34c..6950c8cba8b 100644 --- a/src/main/runtime/orchestration/db/runs/run-binding.ts +++ b/src/main/runtime/orchestration/db/runs/run-binding.ts @@ -42,6 +42,15 @@ export function bindRun( return undefined } const sameBinding = runBoundToCoordinator(run, coordinator) + const peerRun = this.getPeerRun(params.runId) + if (peerRun && !sameBinding) { + // A paired Orca's Run has that Orca as its only consumer; it never binds anything here. + throw new OrchestrationError( + 'consumer_fenced', + `Run ${params.runId} is coordinated from ${peerRun.home_label}, which stays its only coordinator. No effects were applied.`, + { effectsApplied: false } + ) + } const explicitTakeover = params.takeoverLegacy === true // Why: before the legacy gate, so a worker never sees its --takeover-legacy recovery command. const workerRefusal = sameBinding diff --git a/src/main/runtime/orchestration/db/runs/run-create.ts b/src/main/runtime/orchestration/db/runs/run-create.ts index 53b17414ea6..6ce7877082c 100644 --- a/src/main/runtime/orchestration/db/runs/run-create.ts +++ b/src/main/runtime/orchestration/db/runs/run-create.ts @@ -4,42 +4,19 @@ import type { OrchestrationDb } from '../orchestration-db' import type { OrcaSessionId } from '../../../../../shared/orca-session-address' import { mailboxAddressOf } from '../../addressing/orchestration-caller-identity' -export function createRun( - this: OrchestrationDb, - params: { - objective: string - coordinatorHandle: string | null - coordinatorPaneKey: string | null - /** The coordinator's bare Orca session id when it is a structured session; see orca-session-address. */ - coordinatorOrcaSessionId?: OrcaSessionId | null - } -): RunRow { - const coordinator = { - terminalHandle: params.coordinatorHandle, - paneKey: params.coordinatorPaneKey, - orcaSessionId: params.coordinatorOrcaSessionId ?? null - } +type RunCoordinatorParams = { + objective: string + coordinatorHandle: string | null + coordinatorPaneKey: string | null + /** The coordinator's bare Orca session id when it is a structured session; see orca-session-address. */ + coordinatorOrcaSessionId?: OrcaSessionId | null +} + +export function createRun(this: OrchestrationDb, params: RunCoordinatorParams): RunRow { const id = generateId('run') this.db.exec('BEGIN IMMEDIATE') try { - this.db - .prepare( - `INSERT INTO runs ( - id, objective, coordinator_handle, coordinator_pane_key, coordinator_orca_session_id, - coordinator_orca_session_id_generation, consumer_generation, legacy - ) VALUES (?, ?, ?, ?, ?, 1, 1, 0)` - ) - .run( - id, - params.objective, - coordinator.terminalHandle, - coordinator.paneKey, - coordinator.orcaSessionId - ) - const address = mailboxAddressOf(coordinator) - if (address !== null) { - this.rememberRunCoordinatorHandle(id, address) - } + this.insertRunRow(id, params) this.db.exec('COMMIT') } catch (error) { this.db.exec('ROLLBACK') @@ -48,12 +25,45 @@ export function createRun( return this.getRun(id) as RunRow } +/** Writes a Run bound to its coordinator inside the caller's transaction. */ +export function insertRunRow( + this: OrchestrationDb, + id: string, + params: RunCoordinatorParams +): void { + const coordinator = { + terminalHandle: params.coordinatorHandle, + paneKey: params.coordinatorPaneKey, + orcaSessionId: params.coordinatorOrcaSessionId ?? null + } + this.db + .prepare( + `INSERT INTO runs ( + id, objective, coordinator_handle, coordinator_pane_key, coordinator_orca_session_id, + coordinator_orca_session_id_generation, consumer_generation, legacy + ) VALUES (?, ?, ?, ?, ?, 1, 1, 0)` + ) + .run( + id, + params.objective, + coordinator.terminalHandle, + coordinator.paneKey, + coordinator.orcaSessionId + ) + const address = mailboxAddressOf(coordinator) + if (address !== null) { + this.rememberRunCoordinatorHandle(id, address) + } +} + export type RunCreateMethods = { createRun: typeof createRun + insertRunRow: typeof insertRunRow } export function attachRunCreate(ctor: { prototype: object }): void { Object.assign(ctor.prototype, { - createRun + createRun, + insertRunRow }) } diff --git a/src/main/runtime/orchestration/db/schema/create-tables.ts b/src/main/runtime/orchestration/db/schema/create-tables.ts index 1895230e847..5378ee71629 100644 --- a/src/main/runtime/orchestration/db/schema/create-tables.ts +++ b/src/main/runtime/orchestration/db/schema/create-tables.ts @@ -3,9 +3,12 @@ import { createCoreTablesSql } from './create-core-tables-sql' import { createGraphTablesSql } from './create-graph-tables-sql' import { DERIVED_DELIVERY_SCHEMA_SQL } from './migrate-v41' import { REMOVED_WORK_SCHEMA_SQL } from '../reset/removed-orchestration-work-store' +import { PEER_RUN_SCHEMA_SQL } from '../peer-runs/peer-run-queue-sql' export function createTables(this: OrchestrationDb): void { - this.db.exec(`${createCoreTablesSql()}\n${createGraphTablesSql()}\n${REMOVED_WORK_SCHEMA_SQL}`) + this.db.exec( + `${createCoreTablesSql()}\n${createGraphTablesSql()}\n${REMOVED_WORK_SCHEMA_SQL}\n${PEER_RUN_SCHEMA_SQL}` + ) // Unreleased builds saved each send's fence as NOT NULL; nothing reads it, and new rows carry none. if (this.hasColumn('structured_mail_sends', 'fence')) { this.db.exec('ALTER TABLE structured_mail_sends DROP COLUMN fence') diff --git a/src/main/runtime/orchestration/db/tasks/task-store.ts b/src/main/runtime/orchestration/db/tasks/task-store.ts index 401d3d68544..aebef0d890f 100644 --- a/src/main/runtime/orchestration/db/tasks/task-store.ts +++ b/src/main/runtime/orchestration/db/tasks/task-store.ts @@ -10,6 +10,8 @@ import { selectColumns, TASK_COLUMNS } from '../row-column-lists' export function createTask( this: OrchestrationDb, task: { + /** Set only for a Task placed on a paired server: one ID for it here and there, from the start's retry key. */ + id?: string spec: string taskTitle?: string displayName?: string @@ -39,7 +41,7 @@ export function createTask( throw new Error(`Dependency task ${depId} must belong to run ${runId}`) } } - const id = generateId('task') + const id = task.id ?? generateId('task') const depsJson = JSON.stringify(task.deps ?? []) const display = buildOrchestrationTaskDisplayMetadata({ spec: task.spec, diff --git a/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts b/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts index b65da6e2f61..f45cf6677e0 100644 --- a/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts +++ b/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts @@ -18,6 +18,8 @@ export function createStartingWorkerDispatch( params: { taskId?: string taskSpec?: string + /** The paired coordinator's ID for this Task: an existing one is reopened, else the new one takes it. */ + adoptTaskId?: string taskRunId?: string taskCreatedByTerminalHandle?: string taskCreatedByPaneKey?: string @@ -89,26 +91,42 @@ export function createStartingWorkerDispatch( { followUpDispatchId: claimedFollowUp.id } ) } + const adopted = params.adoptTaskId ? this.getTask(params.adoptTaskId) : undefined + if (adopted && !params.retryOf) { + reopenSettledAdoptedTask(this, adopted, params.taskRunId) + } const task = params.taskId ? this.getTask(params.taskId) - : params.taskSpec - ? this.createTask({ - spec: params.taskSpec, - taskTitle: params.taskTitle, - deps: params.taskDeps, - parentId: params.taskParentId, - createdByTerminalHandle: params.taskCreatedByTerminalHandle, - createdByPaneKey: params.taskCreatedByPaneKey, - createdByProcessIncarnation: params.taskCreatedByProcessIncarnation, - createdByRunGeneration: params.taskCreatedByRunGeneration, - runId: params.taskRunId - }) - : undefined + : adopted + ? this.getTask(adopted.id) + : params.taskSpec + ? this.createTask({ + id: params.adoptTaskId, + spec: params.taskSpec, + taskTitle: params.taskTitle, + deps: params.taskDeps, + parentId: params.taskParentId, + createdByTerminalHandle: params.taskCreatedByTerminalHandle, + createdByPaneKey: params.taskCreatedByPaneKey, + createdByProcessIncarnation: params.taskCreatedByProcessIncarnation, + createdByRunGeneration: params.taskCreatedByRunGeneration, + runId: params.taskRunId + }) + : undefined if (!task) { // An inline spec already creates its Task; missing rows here imply an explicit id. const taskId = params.taskId ?? '' throw taskNotFoundError(`Task ${taskId} was not found.`, { taskId }) } + const peerRun = this.getPeerRun(task.run_id) + if (peerRun?.state === 'closed') { + // Starts, follow-ups and helpers alike: its coordinator cancelled it. + throw new OrchestrationError( + 'run_not_found', + `Run ${task.run_id} was cancelled by ${peerRun.home_label}. No effects were applied.`, + { effectsApplied: false } + ) + } let priorFailures = 0 if (params.retryOf) { const prior = this.getDispatchContextById(params.retryOf) @@ -251,3 +269,30 @@ export function attachWorkerDispatchStart(ctor: { prototype: object }): void { createStartingWorkerDispatch }) } + +/** A Task its paired coordinator reopened gets a new attempt here once its latest attempt settled. */ +function reopenSettledAdoptedTask( + db: OrchestrationDb, + task: TaskRow, + runId: string | undefined +): void { + if (task.run_id !== runId) { + throw taskNotFoundError(`Task ${task.id} was not found in Run ${runId ?? ''}.`, { + taskId: task.id + }) + } + const latest = db.getDispatchContext(task.id) + const worker = latest ? db.getWorkerDispatch(latest.id) : undefined + const settled = worker + ? ['succeeded', 'failed', 'stopped', 'abandoned'].includes(worker.state) + : !latest || ['completed', 'failed', 'circuit_broken'].includes(latest.status) + // A pending Task still waits on its dependencies; the ordinary promotion readies it. + if (settled && task.status !== 'ready' && task.status !== 'pending') { + transitionLifecycleWithDb(db.db, { + entity: 'task', + id: task.id, + from: task.status, + to: 'ready' + }) + } +} diff --git a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-listing.ts b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-listing.ts index 3e625c2126c..c2ce51ded5e 100644 --- a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-listing.ts +++ b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-listing.ts @@ -103,6 +103,8 @@ export function listWorkerTerminalResources( pendingApproval: boolean terminationReason: TerminalExitCause['kind'] | null resource: WorkerTerminalResourceRow | null + /** The paired Orca's name when its Run here coordinates this worker. */ + coordinatedFrom: string | null createdAt: string databaseId: number }[] { @@ -170,6 +172,7 @@ export function listWorkerTerminalResources( t.parent_id AS parent_task_id, d.task_id, d.run_id, d.status AS dispatch_status, d.termination_reason, + (SELECT home_label FROM peer_runs WHERE run_id = d.run_id) AS coordinated_from, EXISTS ( SELECT 1 FROM question_threads q WHERE q.dispatch_id = d.id AND q.status = 'pending' @@ -199,6 +202,7 @@ export function listWorkerTerminalResources( termination_reason: TerminalExitCause['kind'] | null pending_input: number pending_approval: number + coordinated_from: string | null created_at: string database_id: number }[] @@ -236,6 +240,7 @@ export function listWorkerTerminalResources( pendingApproval: row.pending_approval === 1, terminationReason: row.termination_reason, resource, + coordinatedFrom: row.coordinated_from, createdAt: row.created_at, databaseId: row.database_id } diff --git a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-waiters.ts b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-waiters.ts index 0e2b13c329d..5b88ac6206d 100644 --- a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-waiters.ts +++ b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-waiters.ts @@ -1,17 +1,18 @@ -import type { OrchestrationDb } from '../../db/orchestration-db' +import type Database from '../../../../sqlite/sync-database' -const waiters = new WeakMap void>>() +const waiters = new WeakMap void>>() -/** Wakes every pull waiting on this store; each re-reads its own conversations. */ -export function notifyPeerMailQueued(db: OrchestrationDb): void { +/** Wakes every pull waiting on this database; each re-reads its own conversations. Called by every + * write that can queue an item home: a reply, a message filed in a Run, a lifecycle change, a reset. */ +export function notifyPeerMailQueued(db: Database.Database): void { for (const wake of waiters.get(db) ?? []) { wake() } } -/** Resolves when a reply is queued, the wait ends, or the caller goes away. */ +/** Resolves when an item may have been queued, the wait ends, or the caller goes away. */ export function waitForPeerMail( - db: OrchestrationDb, + db: Database.Database, timeoutMs: number, signal?: AbortSignal ): Promise { diff --git a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-child-parent.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-child-parent.ts index e0249544e10..be0580a0127 100644 --- a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-child-parent.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-child-parent.ts @@ -1,5 +1,5 @@ import type { OrcaRuntimeService } from '../../orca-runtime' -import type { OrchestrationSessionCaller } from '../addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../addressing/orchestration-caller-identity' import { OrchestrationError } from '../orchestration-error' import { readCallerStoreInstallationId } from '../../hosts/platform-probe/host-descriptor' import { getCanonicalUserDataPath } from '../../../persistence/loading-store/user-data-path' @@ -22,7 +22,7 @@ export async function resolveFederatedChildParent(args: { | 'getRuntimeId' > from: string - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined serverCapabilities: readonly string[] | undefined serverName: string }): Promise< 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 21dd2d80613..d4a6950dfc6 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,4 +1,4 @@ -import type { OrchestrationSessionCaller } from '../addressing/orchestration-caller-identity' +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' @@ -14,5 +14,5 @@ export type FederatedWorkerStartRequest = { taskDeps: string[] | undefined orchestrationMutation?: WorkerStartMutation /** The coordinator's resolved session, when it is one; recorded as the Dispatch creator. */ - callerSession?: OrchestrationSessionCaller + callerSession?: OrchestrationEntryCaller } diff --git a/src/main/runtime/orchestration/workers/launch/worker-dispatch-preamble.ts b/src/main/runtime/orchestration/workers/launch/worker-dispatch-preamble.ts index bc1fa776441..a68c56d5f2e 100644 --- a/src/main/runtime/orchestration/workers/launch/worker-dispatch-preamble.ts +++ b/src/main/runtime/orchestration/workers/launch/worker-dispatch-preamble.ts @@ -10,6 +10,8 @@ export type PreambleParams = { taskSpec: string /** A terminal handle, or a session's `orca_session_id:`; each is labelled by its kind. */ coordinatorHandle: string + /** The paired Orca's name when it coordinates this worker's Run from another computer. */ + coordinatedFrom?: string workerHandle: string devMode?: boolean // Packaged WSL uses orca-ide; other hosts retain their existing launcher. @@ -38,9 +40,11 @@ function isSessionHandle(handle: string): boolean { /** Terminal agents keep their handle's wording; only a session is named by its Orca session ID. */ function dispatchIdentityLines(params: PreambleParams): string { return [ - isSessionHandle(params.coordinatorHandle) - ? `Your coordinator's Orca session ID is: ${params.coordinatorHandle}` - : `Your coordinator's terminal handle is: ${params.coordinatorHandle}`, + params.coordinatedFrom + ? `You are coordinated from ${params.coordinatedFrom}. Your coordinator's address here is: ${params.coordinatorHandle}` + : isSessionHandle(params.coordinatorHandle) + ? `Your coordinator's Orca session ID is: ${params.coordinatorHandle}` + : `Your coordinator's terminal handle is: ${params.coordinatorHandle}`, `Your task ID is: ${params.taskId}`, ...(isSessionHandle(params.workerHandle) ? [`Your Orca session ID is: ${params.workerHandle}`] 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 7f114fd9544..c68dca11f1a 100644 --- a/src/main/runtime/orchestration/workers/launch/worker-start-card.ts +++ b/src/main/runtime/orchestration/workers/launch/worker-start-card.ts @@ -6,7 +6,7 @@ import type { import type { AgentMessageSender } from '../../../../../shared/agent-session/agent-session-message-source' import type { AgentType } from '../../../../../shared/agent-status/contracts/agent-status-types' import type { OrcaRuntimeService } from '../../../orca-runtime' -import type { OrchestrationSessionCaller } from '../../addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../addressing/orchestration-caller-identity' export type AgentCreationCard = AgentJournalAgentStartItem | AgentJournalAgentHandoffItem @@ -48,7 +48,7 @@ export function startedAgentSender( export function prepareWorkerStartCard( runtime: OrcaRuntimeService, - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined ): (args: { dispatchId: string workerAddress: string @@ -56,7 +56,10 @@ export function prepareWorkerStartCard( /** What this start launched; the only kind known for a worker on another host. */ agent: AgentType | null }) => void { - const publish = prepareAgentCreationCard(callerSession?.sessionId) + // A paired Orca has no chat here to show the card in. + const publish = prepareAgentCreationCard( + callerSession?.kind === 'peer' ? undefined : callerSession?.sessionId + ) if (!publish) { return () => {} } diff --git a/src/main/runtime/repositories/repo-icon-fork-backfill.test.ts b/src/main/runtime/repositories/repo-icon-fork-backfill.test.ts index 352aef26709..5849b9c1848 100644 --- a/src/main/runtime/repositories/repo-icon-fork-backfill.test.ts +++ b/src/main/runtime/repositories/repo-icon-fork-backfill.test.ts @@ -1,79 +1,291 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { Repo } from '../../../shared/repo-types' -import * as repoSlugUpstream from '../../github/client/fetch/repo-slug-upstream' -import { OrcaRuntimeService } from '../orca-runtime' -import { repoTarget } from '../../persistence/repo-host-target-matcher.test-fixture' +import { partialRuntimeStore } from '../orca-runtime-tests/runtime-store-partial-fixture' +import { + probeRepoUpstream, + type RepoUpstreamProbe +} from '../../github/client/fetch/repo-slug-upstream' +import { RuntimeRepositoryForkBackfill } from './runtime-repository-fork-backfill' vi.mock('../../github/client/fetch/repo-slug-upstream', async (importOriginal) => ({ ...(await importOriginal>()), - getRepoSlug: vi.fn(), - getRepoUpstream: vi.fn() + probeRepoUpstream: vi.fn() })) - -const getRepoUpstream = vi.mocked(repoSlugUpstream.getRepoUpstream) -const getRepoSlug = vi.mocked(repoSlugUpstream.getRepoSlug) - -type BackfillInternals = { repositoryForkBackfill: { run(): Promise } } - -function makeRepo(overrides: Partial = {}): Repo { +const probe = vi.mocked(probeRepoUpstream) +const origin = { owner: 'me', repo: 'widget', host: 'github.com' } +const originIcon = { + type: 'image', + src: 'https://github.com/me.png?size=64', + source: 'github', + label: 'me/widget' +} +const parent = { owner: 'acme', repo: 'widget', host: 'github.com' } +function makeRepo(id = 'repo-1', overrides: Partial = {}): Repo { return { - id: 'repo-1', - path: '/workspace/rocket-pro', - displayName: 'rocket-pro', - badgeColor: '#2563eb', + id, + path: `/workspace/${id}`, + displayName: 'widget', + badgeColor: 'blue', addedAt: 1, kind: 'git', - repoIcon: { - type: 'image', - src: 'https://github.com/acme.png?size=64', - source: 'github', - label: 'acme/rocket-pro' - }, ...overrides } } - -function attachStore(runtime: OrcaRuntimeService, repos: Repo[]) { +function fixture(repos: Repo[]) { const updateRepo = vi.fn((target: Pick, updates: Partial) => { const index = repos.findIndex((repo) => repo.id === target.id) + if (index === -1) { + return null + } repos[index] = { ...repos[index], ...updates } + return repos[index] }) - Object.assign(runtime, { store: { getRepos: () => repos, updateRepo } }) - return updateRepo + const store = partialRuntimeStore({ + getRepos: () => repos, + getRepo: (id) => repos.find((repo) => repo.id === id), + updateRepo + }) + const notify = vi.fn() + return { + owner: new RuntimeRepositoryForkBackfill(() => store, notify), + repos, + notify, + updateRepo + } } - afterEach(() => { - vi.clearAllMocks() + vi.resetAllMocks() + vi.useRealTimers() }) -describe('startup fork-upstream backfill', () => { - it('keeps an icon chosen while avatar detection is pending', async () => { - const runtime = new OrcaRuntimeService() - const repo = makeRepo() - const repos = [repo] - const updateRepo = attachStore(runtime, repos) - getRepoUpstream.mockResolvedValue({ owner: 'upstream-org', repo: 'rocket' }) - let resolveSlug!: (value: { owner: string; repo: string }) => void - let markSlugStarted!: () => void - const slugStarted = new Promise((resolve) => { - markSlugStarted = resolve - }) - getRepoSlug.mockImplementationOnce( - () => - new Promise((resolve) => { - resolveSlug = resolve - markSlugStarted() - }) - ) - - const backfill = (runtime as unknown as BackfillInternals).repositoryForkBackfill.run() - await slugStarted - repos[0] = { ...repo, repoIcon: { type: 'emoji', emoji: '🚀' } } - resolveSlug({ owner: 'acme', repo: 'rocket-pro' }) - await backfill - - expect(updateRepo).toHaveBeenCalledExactlyOnceWith(repoTarget('repo-1'), { - upstream: { owner: 'upstream-org', repo: 'rocket' } +describe('repository metadata ownership', () => { + it('keeps unavailable parent evidence unknown, fills origin avatar, and recovers on startup', async () => { + const f = fixture([makeRepo()]) + probe + .mockResolvedValueOnce({ upstream: undefined, origin }) + .mockResolvedValueOnce({ upstream: parent, origin }) + await f.owner.run() + expect(f.repos[0].upstream).toBeUndefined() + expect(f.repos[0].repoIcon).toEqual(originIcon) + await f.owner.run() + expect(f.repos[0].upstream).toEqual(parent) + expect(f.repos[0].repoIcon).toEqual({ + ...originIcon, + src: 'https://github.com/acme.png?size=64', + label: 'acme/widget' }) + expect(probe).toHaveBeenCalledTimes(2) + expect(f.notify).toHaveBeenCalledTimes(2) }) + + it('does not reprobe a proved negative or an explicit null icon', async () => { + const f = fixture([makeRepo('negative'), makeRepo('explicit', { repoIcon: null })]) + probe.mockResolvedValue({ upstream: null, origin: null }) + await f.owner.run() + await f.owner.run() + expect(f.repos.map((repo) => repo.upstream)).toEqual([null, null]) + expect(f.repos[1].repoIcon).toBeNull() + expect(probe).toHaveBeenCalledTimes(2) + expect(f.notify).toHaveBeenCalledTimes(1) + }) + + it.each(['removed', 'moved', 'folder', 'chosen-icon', 'selected-origin'] as const)( + 'rejects stale metadata after %s changes while hosted work is pending', + async (change) => { + const f = fixture([makeRepo()]) + const result = Promise.withResolvers() + const started = Promise.withResolvers() + probe.mockImplementationOnce(() => { + started.resolve() + return result.promise + }) + const work = f.owner.run() + await started.promise + if (change === 'removed') { + f.repos.splice(0, 1) + } + if (change === 'moved') { + f.repos[0] = { ...f.repos[0], path: '/elsewhere' } + } + if (change === 'folder') { + f.repos[0] = { ...f.repos[0], kind: 'folder' } + } + if (change === 'chosen-icon') { + f.repos[0] = { ...f.repos[0], repoIcon: { type: 'emoji', emoji: '🚀' } } + } + if (change === 'selected-origin') { + f.repos[0] = { ...f.repos[0], upstream: null } + } + result.resolve({ upstream: parent, origin }) + await work + if (change === 'chosen-icon') { + expect(f.repos[0].repoIcon).toEqual({ type: 'emoji', emoji: '🚀' }) + expect(f.repos[0].upstream).toEqual(parent) + } else if (change === 'selected-origin') { + expect(f.repos[0].upstream).toBeNull() + expect(f.repos[0].repoIcon).toEqual(originIcon) + } else { + expect(f.updateRepo).not.toHaveBeenCalled() + } + } + ) + + it.each([12, 120])( + 'serializes and deduplicates a finite %i-row batch with one notice', + async (count) => { + const f = fixture(Array.from({ length: count }, (_, index) => makeRepo(`repo-${index}`))) + const gate = Promise.withResolvers() + const started = Promise.withResolvers() + let active = 0 + let peak = 0 + probe.mockImplementation(async () => { + active++ + peak = Math.max(peak, active) + started.resolve() + await gate.promise + active-- + return { upstream: null, origin: null } + }) + const batch = f.owner.run() + await started.promise + const duplicate = f.owner.enqueue(f.repos) + const required = f.owner.resolve(f.repos[0]) + gate.resolve({ upstream: null, origin: null }) + await Promise.all([batch, duplicate, required]) + expect(peak).toBe(1) + expect(probe).toHaveBeenCalledTimes(count) + expect(f.updateRepo).toHaveBeenCalledTimes(count) + expect(f.notify).toHaveBeenCalledTimes(1) + await f.owner.run() + expect(probe).toHaveBeenCalledTimes(count) + } + ) + + it('publishes a completed finite batch while a later batch is still pending', async () => { + const f = fixture([makeRepo('first'), makeRepo('later')]) + const first = Promise.withResolvers() + const later = Promise.withResolvers() + probe.mockImplementationOnce(() => first.promise).mockImplementationOnce(() => later.promise) + const a = f.owner.enqueue([f.repos[0]]) + const b = f.owner.enqueue([f.repos[1]]) + first.resolve({ upstream: null, origin: null }) + await a + expect(f.notify).toHaveBeenCalledTimes(1) + later.resolve({ upstream: null, origin: null }) + await b + expect(f.notify).toHaveBeenCalledTimes(2) + }) + + it.each([12, 120])( + 'starts a required row ahead of %i unrelated background rows without duplicating it', + async (count) => { + const f = fixture(Array.from({ length: count }, (_, index) => makeRepo(`repo-${index}`))) + const blocker = Promise.withResolvers() + probe + .mockImplementationOnce(() => blocker.promise) + .mockResolvedValue({ upstream: parent, origin }) + const batch = f.owner.run() + const selected = f.owner.resolve(f.repos[count - 1]) + try { + await vi.waitFor(() => expect(f.repos[count - 1].upstream).toEqual(parent)) + await selected + expect(f.repos[0].upstream).toBeUndefined() + expect( + probe.mock.calls.filter(([path]) => path === `/workspace/repo-${count - 1}`) + ).toHaveLength(1) + } finally { + blocker.resolve({ upstream: null, origin: null }) + await batch + } + expect(probe).toHaveBeenCalledTimes(count) + expect(f.notify).toHaveBeenCalledTimes(1) + } + ) + + it('reserves optional capacity and admits required jobs in request order with at most four active', async () => { + const f = fixture(Array.from({ length: 8 }, (_, index) => makeRepo(`repo-${index}`))) + const pending = new Map>>() + const starts: string[] = [] + let active = 0 + let peak = 0 + probe.mockImplementation(async (path) => { + active++ + peak = Math.max(peak, active) + starts.push(path) + const result = Promise.withResolvers() + pending.set(path, result) + const value = await result.promise + active-- + return value + }) + const batch = f.owner.run() + // Request order differs from the older background inventory order. + const required = [5, 4, 3, 2, 1].map((index) => f.owner.resolve(f.repos[index])) + const join = f.owner.resolve(f.repos[0]) + try { + await vi.waitFor(() => expect(starts).toHaveLength(4)) + expect(starts).toEqual([ + '/workspace/repo-0', + '/workspace/repo-5', + '/workspace/repo-4', + '/workspace/repo-3' + ]) + pending.get('/workspace/repo-4')!.resolve({ upstream: null, origin: null }) + await vi.waitFor(() => expect(starts[4]).toBe('/workspace/repo-2')) + pending.get('/workspace/repo-5')!.resolve({ upstream: null, origin: null }) + await vi.waitFor(() => expect(starts[5]).toBe('/workspace/repo-1')) + expect(peak).toBe(4) + expect(starts).not.toContain('/workspace/repo-6') + } finally { + probe.mockResolvedValue({ upstream: null, origin: null }) + for (const result of pending.values()) { + result.resolve({ upstream: null, origin: null }) + } + await Promise.all([batch, join, ...required]) + } + expect(f.notify).toHaveBeenCalledTimes(1) + expect(probe).toHaveBeenCalledTimes(8) + }) + + it.each([12, 120])( + 'does not serialize protected image payloads across %i rows', + async (count) => { + const icons = Array.from({ length: count }, (_, index) => ({ + type: 'image' as const, + source: index % 2 ? ('upload' as const) : ('file' as const), + src: `data:image/png;base64,${'a'.repeat(350_000)}` + })) + const f = fixture(icons.map((repoIcon, index) => makeRepo(`repo-${index}`, { repoIcon }))) + const gate = Promise.withResolvers() + const started = Promise.withResolvers() + probe + .mockImplementationOnce(() => { + started.resolve() + return gate.promise + }) + .mockResolvedValue({ upstream: parent, origin }) + const protectedIcons = new Set(icons) + const serialized = vi.spyOn(JSON, 'stringify') + const batch = f.owner.run() + await started.promise + // A user replacing the captured protected image with an automatic icon must still survive. + f.repos[0] = { + ...f.repos[0], + repoIcon: { type: 'image', source: 'github', src: 'https://github.com/chosen.png' } + } + gate.resolve({ upstream: parent, origin }) + await batch + const protectedCopies = serialized.mock.calls.filter(([value]) => protectedIcons.has(value)) + serialized.mockRestore() + expect(protectedCopies).toHaveLength(0) + expect(f.repos.every((repo) => repo.upstream?.owner === 'acme')).toBe(true) + expect(f.repos[0].repoIcon).toEqual({ + type: 'image', + source: 'github', + src: 'https://github.com/chosen.png' + }) + expect(f.repos[1].repoIcon).toBe(icons[1]) + expect(f.notify).toHaveBeenCalledTimes(1) + } + ) }) diff --git a/src/main/runtime/repositories/repo-metadata-executable-absence.test.ts b/src/main/runtime/repositories/repo-metadata-executable-absence.test.ts new file mode 100644 index 00000000000..4c7afda5031 --- /dev/null +++ b/src/main/runtime/repositories/repo-metadata-executable-absence.test.ts @@ -0,0 +1,172 @@ +import { chmod, mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createFakeSpawnedChild } from '../../../shared/__fixtures__/fake-spawned-child' +import { partialRuntimeStore } from '../orca-runtime-tests/runtime-store-partial-fixture' +import type { Repo } from '../../../shared/repo-types' + +const { spawnMock, gitMock } = vi.hoisted(() => ({ spawnMock: vi.fn(), gitMock: vi.fn() })) +vi.mock('node:child_process', async (importOriginal) => ({ + ...(await importOriginal>()), + spawn: spawnMock +})) +vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ + ...(await importOriginal>()), + gitExecFileAsync: gitMock +})) + +import { RuntimeRepositoryForkBackfill } from './runtime-repository-fork-backfill' +import { ghExecFileAsync } from '../../git/command-runner/gh-exec-file' +import { GhExecutableAbsenceBatch } from '../../git/command-runner/gh-executable-absence-batch' + +const missing = () => Object.assign(new Error('spawn gh ENOENT'), { code: 'ENOENT', path: 'gh' }) +function successfulSpawn() { + const child = createFakeSpawnedChild(4321) + queueMicrotask(() => { + child.stdout?.emit( + 'data', + Buffer.from('{"isFork":true,"parent":{"owner":{"login":"acme"},"name":"widget"}}') + ) + child.emit('exit', 0, null) + child.emit('close', 0, null) + }) + return child +} + +afterEach(() => { + vi.unstubAllEnvs() + vi.restoreAllMocks() + vi.resetAllMocks() +}) + +describe('finite metadata executable absence', () => { + it.each([12, 120])( + 'shares only the missing executable across a %i-row real probe batch and retries next batch', + async (count) => { + const root = await mkdtemp(join(tmpdir(), 'orca-metadata-absence-')) + const search = join(root, 'bin') + await mkdir(search) + vi.stubEnv('PATH', search) + const repos: Repo[] = [] + for (let i = 0; i < count; i++) { + const path = join(root, `repo-${i}`) + await mkdir(path) + repos.push({ + id: `repo-${i}`, + path, + displayName: 'widget', + kind: 'git', + badgeColor: 'blue', + addedAt: 1 + }) + } + gitMock.mockImplementation(async (args: string[], options: { cwd: string }) => { + if (args[2] === 'origin') { + return { stdout: 'https://github.com/me/widget.git', stderr: '' } + } + if (options.cwd === repos[1].path) { + return { stdout: 'https://github.com/acme/widget.git', stderr: '' } + } + throw Object.assign(new Error('No such remote'), { + code: 2, + stderr: "error: No such remote 'upstream'" + }) + }) + const notify = vi.fn() + const store = partialRuntimeStore({ + getRepos: () => repos, + getRepo: (id) => repos.find((repo) => repo.id === id), + updateRepo: (target, updates) => { + const repo = repos.find((repo) => repo.id === target.id) + if (!repo) { + return null + } + Object.assign(repo, updates) + return repo + } + }) + const owner = new RuntimeRepositoryForkBackfill(() => store, notify) + spawnMock.mockImplementation(() => { + throw missing() + }) + try { + await owner.run() + expect(spawnMock).toHaveBeenCalledTimes(1) + expect(repos[0].upstream).toBeUndefined() + expect(repos[0].repoIcon).toEqual({ + type: 'image', + source: 'github', + src: 'https://github.com/me.png?size=64', + label: 'me/widget' + }) + expect(repos[1].upstream).toEqual({ owner: 'acme', repo: 'widget', host: 'github.com' }) + expect(notify).toHaveBeenCalledTimes(1) + spawnMock.mockImplementation(successfulSpawn) + await owner.run() + expect(repos.every((repo) => repo.upstream?.owner === 'acme')).toBe(true) + expect(spawnMock).toHaveBeenCalledTimes(count) + expect(notify).toHaveBeenCalledTimes(2) + } finally { + await rm(root, { recursive: true, force: true }) + } + } + ) + + it('does not suppress a fresh explicit lookup, changed search context, or per-repository API failure', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-metadata-search-')) + const other = join(root, 'other') + await mkdir(other) + const batch = new GhExecutableAbsenceBatch() + const options = { cwd: root, env: { PATH: root } } + spawnMock.mockImplementation(() => { + throw missing() + }) + try { + await expect( + batch.run(() => ghExecFileAsync(['repo', 'view', 'me/widget'], options)) + ).rejects.toThrow('ENOENT') + await expect( + batch.run(() => ghExecFileAsync(['repo', 'view', 'me/widget'], options)) + ).rejects.toThrow('ENOENT') + expect(spawnMock).toHaveBeenCalledTimes(1) + await expect( + batch.run(() => + ghExecFileAsync(['repo', 'view', 'me/widget'], { ...options, env: { PATH: other } }) + ) + ).rejects.toThrow('ENOENT') + expect(spawnMock).toHaveBeenCalledTimes(2) + spawnMock.mockImplementation(successfulSpawn) + // A required action runs outside the batch's absence evidence and invalidates it on success. + await ghExecFileAsync(['repo', 'view', 'me/widget'], options) + await batch.run(() => ghExecFileAsync(['repo', 'view', 'me/widget'], options)) + expect(spawnMock).toHaveBeenCalledTimes(4) + spawnMock.mockImplementationOnce(() => { + throw new Error('repository not authorized') + }) + await expect( + batch.run(() => ghExecFileAsync(['repo', 'view', 'private/widget'], options)) + ).rejects.toThrow('not authorized') + await batch.run(() => ghExecFileAsync(['repo', 'view', 'public/widget'], options)) + expect(spawnMock).toHaveBeenCalledTimes(6) + // An existing wrapper with an absent interpreter is not proof that gh is absent. + await writeFile( + join(root, process.platform === 'win32' ? 'gh.exe' : 'gh'), + '#!/missing/interpreter\n' + ) + await chmod(join(root, process.platform === 'win32' ? 'gh.exe' : 'gh'), 0o755) + spawnMock.mockImplementation(() => { + throw missing() + }) + for (let i = 0; i < 2; i++) { + await expect( + batch.run(() => ghExecFileAsync(['repo', 'view', 'me/widget'], options)) + ).rejects.toThrow('ENOENT') + } + expect(spawnMock).toHaveBeenCalledTimes(8) + } finally { + batch.close() + await rm(root, { recursive: true, force: true }) + } + }) +}) diff --git a/src/main/runtime/repositories/runtime-project-host-setup-controller.ts b/src/main/runtime/repositories/runtime-project-host-setup-controller.ts index 87fd723ece6..5a0cb4ce49a 100644 --- a/src/main/runtime/repositories/runtime-project-host-setup-controller.ts +++ b/src/main/runtime/repositories/runtime-project-host-setup-controller.ts @@ -20,7 +20,10 @@ import { type ExecutionHostId } from '../../../shared/execution-host' import { getProjectHostSetupForRepo } from '../../../shared/project-host-setup-lookup' -import { resolveImportedFolderProjectLink } from '../../../shared/imported-folder-project-identity' +import { + linkImportedFolderToProject, + type RepositoryMetadataOwner +} from '../../workspaces/catalog/imported-folder-project-link' import { invalidateAuthorizedRootsCache } from '../../ipc/worktrees/removal/registered-worktree-roots-cache' import { SshHostNotServedError } from '../../providers/ssh-host-not-served-error' import { runWorktreeChangeInvalidators } from '../../ipc/worktrees/listing/worktree-change-invalidators' @@ -47,7 +50,7 @@ import { type ProjectHostSetupTarget } from '../../../shared/project-host-setup-target' -type RuntimeProjectHostSetupDependencies = { +type RuntimeProjectHostSetupDependencies = RepositoryMetadataOwner & { getStore: () => RuntimeStore | null listRepos: () => Repo[] addRepo: (path: string, kind: 'folder' | 'git', hostId: ExecutionHostId) => Promise @@ -260,14 +263,16 @@ export class RuntimeProjectHostSetupController { } } - private completeSetup( + private async completeSetup( args: ProjectHostSetupExistingFolderArgs, initialRepo: Repo, repoWasCreated: boolean, folderRemote: Pick - ): ProjectHostSetupResult { + ): Promise { try { - return this.linkRepo(args, initialRepo, folderRemote) + const result = await this.linkRepo(args, initialRepo, folderRemote) + this.deps.notifyReposChanged() + return result } catch (error) { if (repoWasCreated) { // Rollback must remove only this host's row, never a same-id sibling. @@ -275,53 +280,25 @@ export class RuntimeProjectHostSetupController { this.deps.invalidateResolvedWorktrees() this.deps.invalidateWorktreeScan(initialRepo.id) invalidateAuthorizedRootsCache() - this.deps.notifyReposChanged() } + this.deps.notifyReposChanged() throw error } } - private linkRepo( + private async linkRepo( args: ProjectHostSetupExistingFolderArgs, initialRepo: Repo, folderRemote: Pick - ): ProjectHostSetupResult { - const store = this.deps.getStore() - if (!store) { - throw new Error('runtime_unavailable') - } - assertWslMoveHostSetupWritable(store, { - projectId: args.projectId, - hostId: getRepoExecutionHostId(initialRepo), - repoId: initialRepo.id - }) - let repo = initialRepo - let setup = getProjectHostSetupForRepo(this.listSetups(), repo) - if (setup.projectId !== args.projectId) { - const existingProject = this.listProjects().find((project) => project.id === args.projectId) - const updated = store.updateRepo( - repo, - resolveImportedFolderProjectLink( - { ...repo, ...folderRemote }, - args.projectId, - existingProject?.providerIdentity ?? args.projectProviderIdentity - ) - ) - if (!updated) { - throw new Error(`Project setup repo disappeared before it could be linked: ${repo.id}`) - } - repo = updated - setup = getProjectHostSetupForRepo(this.listSetups(), repo) - } - const setupMethod = args.setupMethod ?? 'imported-existing-folder' - const updated = store.updateRepo(repo, { projectHostSetupMethod: setupMethod }) - if (!updated) { - throw new Error( - `Project setup repo disappeared before setup metadata could be linked: ${repo.id}` - ) - } - repo = updated - setup = getProjectHostSetupForRepo(this.listSetups(), repo) + ): Promise { + const repo = await linkImportedFolderToProject( + this.deps.getStore, + initialRepo, + folderRemote, + args, + this.deps + ) + const setup = getProjectHostSetupForRepo(this.listSetups(), repo) const project = this.listProjects().find((entry) => entry.id === setup.projectId) if (!project) { throw new Error(`Project setup was created without a project record: ${setup.projectId}`) diff --git a/src/main/runtime/repositories/runtime-project-host-setup-git-remote-link.test.ts b/src/main/runtime/repositories/runtime-project-host-setup-git-remote-link.test.ts index 57936ac536f..718f6c32c17 100644 --- a/src/main/runtime/repositories/runtime-project-host-setup-git-remote-link.test.ts +++ b/src/main/runtime/repositories/runtime-project-host-setup-git-remote-link.test.ts @@ -26,6 +26,7 @@ async function clonedRepo(remoteUrl: string): Promise { function makeController(cloned: Repo) { const repos: Repo[] = [] const store = { + getRepos: () => repos, getProjects: () => projectHostSetupProjectionFromRepos(repos).projects, getProjectHostSetups: () => projectHostSetupProjectionFromRepos(repos).setups, updateRepo: ({ id }: Pick, updates: Partial) => { @@ -55,6 +56,8 @@ function makeController(cloned: Repo) { invalidateResolvedWorktrees: vi.fn(), invalidateWorktreeScan: vi.fn(), notifyReposChanged: vi.fn(), + enqueueRepositoryMetadata: vi.fn(), + resolveRepositoryMetadata: vi.fn().mockResolvedValue(true), countLiveTerminalsForRepo: () => 0 }) return { controller, repos } diff --git a/src/main/runtime/repositories/runtime-repository-clone-controller.ts b/src/main/runtime/repositories/runtime-repository-clone-controller.ts index 7d74b2272e3..92fc7def209 100644 --- a/src/main/runtime/repositories/runtime-repository-clone-controller.ts +++ b/src/main/runtime/repositories/runtime-repository-clone-controller.ts @@ -23,7 +23,7 @@ import type { } from '../../../shared/git/clone/clone-target-check' import { runWithGitReadCacheInvalidation } from '../../git/source-control/git-read-cache-invalidation' import { invalidateAuthorizedRootsCache } from '../../ipc/worktrees/removal/registered-worktree-roots-cache' -import { detectRepoIconAndUpstream } from '../../repository-icons/repo-icon-autodetect' +import { detectRepoLocalMetadata } from '../../repository-icons/repo-icon-autodetect' import { getRepoName } from '../../git/repo' import { inspectGitRepoForRegistrationAsync } from '../../git/repo-detection' import { prepareLocalWorktreeRootForRepo } from '../../workspaces/creation/worktree-root-preparation' @@ -216,7 +216,7 @@ export class RuntimeRepositoryCloneController { // cloneRepo validated and cloned locally; runtime row stamps do not change where files live. // Register Git's checkout path so the clone stays its own selected checkout. const repoPath = (await inspectGitRepoForRegistrationAsync(clonePath)).rootPath - const detected = await detectRepoIconAndUpstream({ + const detected = await detectRepoLocalMetadata({ repoPath, kind: 'git', executionHostId: LOCAL_EXECUTION_HOST_ID diff --git a/src/main/runtime/repositories/runtime-repository-clone-host-dedupe.test.ts b/src/main/runtime/repositories/runtime-repository-clone-host-dedupe.test.ts index d4840037fed..869a7504ff3 100644 --- a/src/main/runtime/repositories/runtime-repository-clone-host-dedupe.test.ts +++ b/src/main/runtime/repositories/runtime-repository-clone-host-dedupe.test.ts @@ -9,7 +9,7 @@ import { RuntimeRepositoryCloneController } from './runtime-repository-clone-con import type { RuntimeStore } from '../construction/runtime-store-contract' vi.mock('../../repository-icons/repo-icon-autodetect', () => ({ - detectRepoIconAndUpstream: vi.fn().mockResolvedValue({}) + detectRepoLocalMetadata: vi.fn().mockResolvedValue({}) })) vi.mock('../../workspaces/creation/worktree-root-preparation', () => ({ prepareLocalWorktreeRootForRepo: vi.fn().mockResolvedValue(undefined) diff --git a/src/main/runtime/repositories/runtime-repository-command-surface.ts b/src/main/runtime/repositories/runtime-repository-command-surface.ts index 8cc6306f3fb..4bf48c0edf9 100644 --- a/src/main/runtime/repositories/runtime-repository-command-surface.ts +++ b/src/main/runtime/repositories/runtime-repository-command-surface.ts @@ -3,6 +3,7 @@ import type { RuntimeHostedReviewCommands } from '../integrations/reviews/runtim import type { RuntimeNestedRepoImport } from './runtime-nested-repo-import' import type { RuntimeProjectGroupController } from './runtime-project-group-controller' import type { RuntimeProjectHostSetupController } from './runtime-project-host-setup-controller' +import type { RuntimeRepositoryForkBackfill } from './runtime-repository-fork-backfill' import type { RuntimeRepositoryCloneController } from './runtime-repository-clone-controller' import type { RuntimeRepositoryHooksCommands } from './runtime-repository-hooks-commands' import type { RuntimeRepositoryIssueCommand } from './runtime-repository-issue-command' @@ -97,7 +98,9 @@ type RuntimeRepositoryCommandOwners = { } export function installRuntimeRepositoryCommandSurface( - target: RuntimeRepositoryCommandSurface, + target: RuntimeRepositoryCommandSurface & { + readonly repositoryForkBackfill: RuntimeRepositoryForkBackfill + }, owners: RuntimeRepositoryCommandOwners ): void { const host = owners.projectHostSetups @@ -142,9 +145,23 @@ export function installRuntimeRepositoryCommandSurface( isGitAvailable: server.isGitAvailable.bind(server), listSparsePresets: sparse.list.bind(sparse), saveSparsePreset: sparse.save.bind(sparse), - addRepo: registrations.add.bind(registrations), - createRepo: registrations.create.bind(registrations), - cloneRepo: clones.clone.bind(clones), + addRepo: async (...args: Parameters) => { + const repo = await registrations.add(...args) + void target.repositoryForkBackfill.enqueue([repo]) + return repo + }, + createRepo: async (...args: Parameters) => { + const result = await registrations.create(...args) + if ('repo' in result) { + void target.repositoryForkBackfill.enqueue([result.repo]) + } + return result + }, + cloneRepo: async (...args: Parameters) => { + const repo = await clones.clone(...args) + void target.repositoryForkBackfill.enqueue([repo]) + return repo + }, checkCloneTarget: clones.checkTarget.bind(clones), showRepo: settings.show.bind(settings), setRepoBaseRef: settings.setBaseRef.bind(settings), diff --git a/src/main/runtime/repositories/runtime-repository-fork-backfill.ts b/src/main/runtime/repositories/runtime-repository-fork-backfill.ts index 94bedda433a..c4682c4c489 100644 --- a/src/main/runtime/repositories/runtime-repository-fork-backfill.ts +++ b/src/main/runtime/repositories/runtime-repository-fork-backfill.ts @@ -1,18 +1,30 @@ -import { - getRepoExecutionHostId, - getRepoSshConnectionId, - LOCAL_EXECUTION_HOST_ID -} from '../../../shared/execution-host' -import type { GitHubOwnerRepo } from '../../../shared/github/pull-request-types' +import { getRepoExecutionHostId, getRepoSshConnectionId } from '../../../shared/execution-host' import type { Repo } from '../../../shared/repo-types' -import { getRepoUpstream } from '../../github/client/fetch/repo-slug-upstream' -import { detectGitHubAvatarIcon } from '../../repository-icons/repo-icon-autodetect' +import { githubAvatarIcon, githubAvatarSlug } from '../../../shared/repo-icon' +import { probeRepoUpstream } from '../../github/client/fetch/repo-slug-upstream' +import { GhExecutableAbsenceBatch } from '../../git/command-runner/gh-executable-absence-batch' import type { RuntimeStore } from '../construction/runtime-store-contract' import { isWslMoveRepoBlocked } from '../../persistence/moving-wsl-projects/wsl-move-background-backoff' import { blockedWslDistroForPath, wslDistroForPath } from '../../wsl/filesystem/wsl-unc-access-gate' +type MetadataJob = { + store: RuntimeStore + repo: Repo + background: boolean + active: boolean + required: boolean + batch?: GhExecutableAbsenceBatch + done: Promise + finish: (changed: boolean) => void +} + export class RuntimeRepositoryForkBackfill { private started = false + private active = 0 + private backgroundActive = 0 + private readonly jobs = new Map>() + private readonly requiredQueue = new Set() + private readonly backgroundQueue = new Set() constructor( private readonly getStore: () => RuntimeStore | null, @@ -27,64 +39,204 @@ export class RuntimeRepositoryForkBackfill { void this.run() } - async run(): Promise { + run(): Promise { + return this.enqueue( + (this.getStore()?.getRepos() ?? []).filter((repo) => repo.upstream === undefined) + ) + } + + async enqueue(repos: readonly Repo[]): Promise { + const batch: Promise[] = [] + const availability = new GhExecutableAbsenceBatch() try { - const store = this.getStore() - if (!store) { - throw new Error('runtime_unavailable') + for (const repo of repos) { + const job = this.admit(repo) + if (!job || job.background) { + continue + } + job.background = true + job.batch = availability + if (!job.required && !job.active) { + this.backgroundQueue.add(job) + } + batch.push(job.done) } - let changed = false - for (const repo of store.getRepos()) { - // Resolve executionHostId too: raw connectionId misses SSH-only rows, whose gh/Git must never run here. - // WSL-move-fenced repos keep upstream unset for next startup retry. - if ( - repo.upstream !== undefined || - repo.kind === 'folder' || - getRepoSshConnectionId(repo) || - isWslMoveRepoBlocked(repo) - ) { - continue - } - // E9: gh/Git on a stopped distro's repo boots it; upstream stays unset for the next pass. - if (wslDistroForPath(repo.path) && (await blockedWslDistroForPath(repo.path))) { - continue - } - let upstream: GitHubOwnerRepo | null - try { - upstream = await getRepoUpstream(repo.path, null) - } catch { - continue - } - const repoIcon = - upstream && repo.repoIcon?.type === 'image' && repo.repoIcon.source === 'github' - ? await detectGitHubAvatarIcon(repo.path, LOCAL_EXECUTION_HOST_ID, upstream) - : null - // Qualify by host: WSL moves leave hidden local rows beside same-id host rows. - const hostId = getRepoExecutionHostId(repo) - const current = store - .getRepos() - .find( - (candidate) => candidate.id === repo.id && getRepoExecutionHostId(candidate) === hostId - ) - if (!current || current.upstream !== undefined || isWslMoveRepoBlocked(current)) { - continue - } - const updates: Partial = { upstream: upstream ?? null } - if ( - repoIcon && - current.repoIcon?.type === 'image' && - current.repoIcon.source === 'github' - ) { - updates.repoIcon = repoIcon - } - store.updateRepo(current, updates) - changed = true - } - if (changed) { + this.drain() + // Each admitted finite batch owns its notice, independent of later arrivals. + const changes = await Promise.all(batch) + if (changes.some(Boolean)) { this.notifyChanged() } - } catch { - // Best-effort startup migration. + } finally { + availability.close() } } + + async resolve(repo: Repo): Promise { + if (this.current(this.getStore(), repo)?.upstream !== undefined) { + return true + } + const job = this.admit(repo) + if (!job) { + return false + } + if (!job.required && !job.active) { + this.backgroundQueue.delete(job) + this.requiredQueue.add(job) + } + job.required = true + this.drain() + await job.done + return true + } + + private key(repo: Repo): string { + return `${repo.id}\0${getRepoExecutionHostId(repo)}\0${repo.path}\0${repo.kind}` + } + + private current(store: RuntimeStore | null, snapshot: Repo): Repo | undefined { + if (!store || store !== this.getStore()) { + return undefined + } + const host = getRepoExecutionHostId(snapshot) + const found = store.getRepo(snapshot.id) + const row = + found && getRepoExecutionHostId(found) === host + ? found + : store + .getRepos() + .find( + (candidate) => + candidate.id === snapshot.id && getRepoExecutionHostId(candidate) === host + ) + return row && + row.path === snapshot.path && + row.kind === snapshot.kind && + row.kind !== 'folder' && + !getRepoSshConnectionId(row) && + !isWslMoveRepoBlocked(row) + ? row + : undefined + } + + private admit(repo: Repo): MetadataJob | undefined { + const store = this.getStore() + const current = this.current(store, repo) + if (!store || !current || (current.upstream !== undefined && current.repoIcon !== undefined)) { + return undefined + } + let jobs = this.jobs.get(store) + if (!jobs) { + this.jobs.set(store, (jobs = new Map())) + } + const key = this.key(current) + const existing = jobs.get(key) + if (existing) { + return existing + } + let finish!: MetadataJob['finish'] + const done = new Promise((resolve) => { + finish = resolve + }) + const job: MetadataJob = { + store, + repo: { ...current }, + background: false, + active: false, + required: false, + done, + finish + } + jobs.set(key, job) + return job + } + + private drain(): void { + while (this.active < 4) { + const queue = this.requiredQueue.size ? this.requiredQueue : this.backgroundQueue + if (queue === this.backgroundQueue && this.backgroundActive > 0) { + return + } + const job = queue.values().next().value + if (!job) { + return + } + queue.delete(job) + job.active = true + this.active++ + const background = !job.required + if (background) { + this.backgroundActive++ + } + void this.processJob(job, background) + } + } + + private async processJob(job: MetadataJob, background: boolean): Promise { + let changed = false + try { + changed = await (background && job.batch + ? job.batch.run(() => this.probe(job)) + : this.probe(job)) + } catch { + /* Optional metadata stays retryable. */ + } finally { + this.active-- + if (background) { + this.backgroundActive-- + } + this.retire(job, changed) + this.drain() + } + } + + private retire(job: MetadataJob, changed: boolean): void { + const jobs = this.jobs.get(job.store) + jobs?.delete(this.key(job.repo)) + if (jobs?.size === 0) { + this.jobs.delete(job.store) + } + job.finish(changed) + } + + private async probe(job: MetadataJob): Promise { + const { store, repo } = job + let current = this.current(store, repo) + if (!current) { + return false + } + if (wslDistroForPath(repo.path) && (await blockedWslDistroForPath(repo.path))) { + return false + } + current = this.current(store, repo) + if (!current) { + return false + } + const result = await probeRepoUpstream(repo.path, null, {}, current.upstream === undefined) + current = this.current(store, repo) + if (!current) { + return false + } + const updates: Partial = {} + if (current.upstream === undefined && result.upstream !== undefined) { + updates.upstream = result.upstream + } + if ( + current.repoIcon === undefined || + (current.repoIcon?.type === 'image' && + current.repoIcon.source === 'github' && + repo.repoIcon?.type === 'image' && + repo.repoIcon.source === 'github' && + JSON.stringify(current.repoIcon) === JSON.stringify(repo.repoIcon)) + ) { + // Defined null is an explicit origin choice or a proved negative, never the late parent. + const upstream = current.upstream === undefined ? result.upstream : current.upstream + const slug = githubAvatarSlug(result.origin, upstream) + const icon = slug ? githubAvatarIcon(slug) : undefined + if (icon && JSON.stringify(icon) !== JSON.stringify(current.repoIcon)) { + updates.repoIcon = icon + } + } + return Object.keys(updates).length > 0 && !!store.updateRepo(current, updates) + } } diff --git a/src/main/runtime/repositories/runtime-repository-registration-controller.test.ts b/src/main/runtime/repositories/runtime-repository-registration-controller.test.ts index 5374f64d9a1..8584ec06815 100644 --- a/src/main/runtime/repositories/runtime-repository-registration-controller.test.ts +++ b/src/main/runtime/repositories/runtime-repository-registration-controller.test.ts @@ -9,7 +9,7 @@ import { RuntimeRepositoryRegistrationController } from './runtime-repository-re import { partialRuntimeStore } from '../orca-runtime-tests/runtime-store-partial-fixture' vi.mock('../../repository-icons/repo-icon-autodetect', () => ({ - detectRepoIconAndUpstream: vi.fn().mockResolvedValue({}) + detectRepoLocalMetadata: vi.fn().mockResolvedValue({}) })) vi.mock('../../workspaces/creation/worktree-root-preparation', () => ({ prepareLocalWorktreeRootForRepo: vi.fn().mockResolvedValue(undefined) diff --git a/src/main/runtime/repositories/runtime-repository-registration-controller.ts b/src/main/runtime/repositories/runtime-repository-registration-controller.ts index bca8931391f..61d975024ee 100644 --- a/src/main/runtime/repositories/runtime-repository-registration-controller.ts +++ b/src/main/runtime/repositories/runtime-repository-registration-controller.ts @@ -16,7 +16,7 @@ import { getClonePathComparisonKey, getSavedProjectPathKeys } from '../../git/re import { invalidateAuthorizedRootsCache } from '../../ipc/worktrees/removal/registered-worktree-roots-cache' import { isENOENT } from '../../ipc/filesystem/access/filesystem-path-containment' import { findProjectAtSameRealPath } from '../../workspaces/catalog/project-realpath-identity' -import { detectRepoIconAndUpstream } from '../../repository-icons/repo-icon-autodetect' +import { detectRepoLocalMetadata } from '../../repository-icons/repo-icon-autodetect' import { prepareLocalWorktreeRootForRepo } from '../../workspaces/creation/worktree-root-preparation' import type { RuntimeStore } from '../construction/runtime-store-contract' import { runtimePathsEqual } from '../workspaces/catalog/runtime-worktree-path-identity' @@ -96,7 +96,7 @@ export class RuntimeRepositoryRegistrationController { return this.reuseExisting(store, existing, executionHostId) } // This controller validated/read the path locally; runtime: is the paired-client address, not another machine. - const detected = await detectRepoIconAndUpstream({ + const detected = await detectRepoLocalMetadata({ repoPath, kind, executionHostId: LOCAL_EXECUTION_HOST_ID @@ -229,7 +229,7 @@ export class RuntimeRepositoryRegistrationController { repoKind === 'git' ? (await inspectGitRepoForRegistrationAsync(targetPath)).rootPath : targetPath - const detected = await detectRepoIconAndUpstream({ + const detected = await detectRepoLocalMetadata({ repoPath, kind: repoKind, executionHostId: LOCAL_EXECUTION_HOST_ID diff --git a/src/main/runtime/rpc/core.ts b/src/main/runtime/rpc/core.ts index 729f5cf8e54..f135d2ae3f8 100644 --- a/src/main/runtime/rpc/core.ts +++ b/src/main/runtime/rpc/core.ts @@ -20,7 +20,7 @@ import type { DelegatedMobileDeviceSyncResult } from '../../../shared/delegated-mobile-device-contract' import type { OrchestrationCompatibilityEvidence } from '../../../shared/orchestration/orchestration-compatibility-evidence' -import type { OrchestrationSessionCaller } from '../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../orchestration/addressing/orchestration-caller-identity' import type { RpcCallerIdentity } from './rpc-caller-identity' import type { OrcadPeerDesktopsResult } from '../../../shared/orcad-peer-desktops-contract' import type { RpcBinarySender } from './rpc-binary-sender' @@ -91,6 +91,8 @@ export type RpcRequest = { params?: unknown orchestrationContractVersion?: number orchestrationRequestId?: string + // Untrusted wire input; only a paired Orca's runtime pairing admits it (orchestration-peer-caller). + orchestrationPeerRun?: unknown compatibilityInvocationId?: string orchestrationCompatibilityEvidence?: OrchestrationCompatibilityEvidence // Untrusted wire evidence; runtime-source-admission validates it. @@ -151,8 +153,8 @@ export type RpcContext = { replayedMutationReceipt?: unknown // Compare declared Run handles against request attestation. orchestrationCompatibilityEvidence?: OrchestrationCompatibilityEvidence - // Resolve the injected Orca session id once at dispatch; session identity wins. - orchestrationCaller?: OrchestrationSessionCaller + // Resolved once at dispatch from a session's environment or a paired Orca's pairing; it wins. + orchestrationCaller?: OrchestrationEntryCaller // Only the trusted compatibility router sets this; params cannot bypass Run consumer binding. legacyCoordinatorRunId?: string legacyCoordinatorAuthority?: LegacyCoordinatorAuthorityProof diff --git a/src/main/runtime/rpc/dispatcher-stream-options.ts b/src/main/runtime/rpc/dispatcher-stream-options.ts index 551b7db074d..21b77e43870 100644 --- a/src/main/runtime/rpc/dispatcher-stream-options.ts +++ b/src/main/runtime/rpc/dispatcher-stream-options.ts @@ -1,6 +1,6 @@ import type { OrcaRuntimeService } from '../orca-runtime' import { captureStructuredAgentCliSource } from '../../native-chat/structured-agent-cli-source' -import type { OrchestrationSessionCaller } from '../orchestration/addressing/orchestration-caller-identity' +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' @@ -41,7 +41,7 @@ export function rpcContextFromTransport( runtime: OrcaRuntimeService, request: RpcRequest, options: RpcDispatchStreamingOptions | undefined, - orchestrationCaller: OrchestrationSessionCaller | undefined, + orchestrationCaller: OrchestrationEntryCaller | undefined, params?: unknown ): RpcContext { return { diff --git a/src/main/runtime/rpc/dispatcher.ts b/src/main/runtime/rpc/dispatcher.ts index a4daf612975..6262e75373b 100644 --- a/src/main/runtime/rpc/dispatcher.ts +++ b/src/main/runtime/rpc/dispatcher.ts @@ -15,7 +15,7 @@ import { withoutMethodsThisHostDoesNotServe } from './methods/terminal/session-t import { emulatorProbe, emulatorProbeError } from '../../emulator/emulator-probe' import type { OrcaRuntimeService } from '../orca-runtime' import { isDurableMutation } from '../../../shared/orchestration/orchestration-rpc-contract' -import type { OrchestrationSessionCaller } from '../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../orchestration/addressing/orchestration-caller-identity' import { getOrchestrationMutationExecutor, type DurableMutationInvocation, @@ -45,7 +45,7 @@ type AdmittedUnaryCall = { request: RpcRequest method: RpcMethod params: unknown - caller: OrchestrationSessionCaller | undefined + caller: OrchestrationEntryCaller | undefined } export class RpcDispatcher { @@ -231,7 +231,11 @@ export class RpcDispatcher { return desktopBrowser.result } - const compatibility = await legacyOrchestration.tryHandle(request, params, context.signal) + // A paired Orca is never a legacy caller, so its calls reach only the declared access check. + const compatibility = + caller?.kind === 'peer' + ? { handled: false as const } + : await legacyOrchestration.tryHandle(request, params, context.signal) if (compatibility.handled) { return compatibility.result } @@ -252,22 +256,26 @@ export class RpcDispatcher { legacyCoordinator?.mutationCallerFingerprint ?? fallbackCallerFingerprint const invoke = (mutation?: DurableMutationInvocation) => { const legacyCoordinatorRunId = legacyCoordinator?.revalidate() - return runWithActiveRpcCaller(context.caller, () => - method.handler(effectiveParams, { - ...context, - authenticatedCallerFingerprint: mutation?.identity.callerFingerprint ?? callerFingerprint, - recordMutationReceipt: mutation?.recordReceipt, - markWorkerDoneMutationEffectFree: mutation?.markWorkerDoneEffectFree, - markMutationEffectPossible: mutation?.markEffectPossible, - orchestrationMutation: mutation?.identity, - replayedMutationReceipt: mutation?.replayedReceipt, - legacyCoordinatorRunId, - legacyCoordinatorAuthority: legacyCoordinator?.authority, - revalidateLegacyCoordinator: legacyCoordinator?.revalidate, - orchestrationCompatibilityCallerAuthority: - compatibility.orchestrationCompatibilityCallerAuthority, - orchestrationCompatibilityEvidence: request.orchestrationCompatibilityEvidence - }) + return runWithActiveRpcCaller( + context.caller, + () => + method.handler(effectiveParams, { + ...context, + authenticatedCallerFingerprint: + mutation?.identity.callerFingerprint ?? callerFingerprint, + recordMutationReceipt: mutation?.recordReceipt, + markWorkerDoneMutationEffectFree: mutation?.markWorkerDoneEffectFree, + markMutationEffectPossible: mutation?.markEffectPossible, + orchestrationMutation: mutation?.identity, + replayedMutationReceipt: mutation?.replayedReceipt, + legacyCoordinatorRunId, + legacyCoordinatorAuthority: legacyCoordinator?.authority, + revalidateLegacyCoordinator: legacyCoordinator?.revalidate, + orchestrationCompatibilityCallerAuthority: + compatibility.orchestrationCompatibilityCallerAuthority, + orchestrationCompatibilityEvidence: request.orchestrationCompatibilityEvidence + }), + request.orchestrationCompatibilityEvidence?.agentSessionId ) } const result = await orchestrationMutations.run( @@ -275,7 +283,7 @@ export class RpcDispatcher { effectiveParams, invoke, callerFingerprint, - context.orchestrationCaller?.orcaSessionId + context.orchestrationCaller ) if (request.method.startsWith('orchestration.')) { queueMicrotask(() => { diff --git a/src/main/runtime/rpc/methods/browser/browser-core.ts b/src/main/runtime/rpc/methods/browser/browser-core.ts index d9d6d14ed1f..6edf1f772ba 100644 --- a/src/main/runtime/rpc/methods/browser/browser-core.ts +++ b/src/main/runtime/rpc/methods/browser/browser-core.ts @@ -118,6 +118,12 @@ export const BROWSER_CORE_METHODS = [ params: TabCurrent, handler: async (params, { runtime }) => runtime.browserTabCurrent(params) }), + defineMethod({ + name: 'browser.tabAnnotations', + permission: 'workspace', + params: BrowserTarget, + handler: async (params, { runtime }) => runtime.browserTabAnnotations(params) + }), defineMethod({ name: 'browser.tabSwitch', permission: 'workspace', diff --git a/src/main/runtime/rpc/methods/browser/desktop-browser-bridge.ts b/src/main/runtime/rpc/methods/browser/desktop-browser-bridge.ts index eac4e3e6047..8780e8f932b 100644 --- a/src/main/runtime/rpc/methods/browser/desktop-browser-bridge.ts +++ b/src/main/runtime/rpc/methods/browser/desktop-browser-bridge.ts @@ -2,6 +2,7 @@ import { DESKTOP_BROWSER_BRIDGE_CANCEL_CAPABILITY, DESKTOP_BROWSER_BRIDGE_EXPECT_URL_CAPABILITY, DESKTOP_BROWSER_BRIDGE_RUNTIME_CAPABILITY, + DESKTOP_BROWSER_BRIDGE_TAB_ANNOTATIONS_CAPABILITY, DesktopBrowserBridgeAttachParams, DesktopBrowserBridgeResultParams } from '../../../../../shared/desktop-browser-bridge-protocol' @@ -45,6 +46,9 @@ export const DESKTOP_BROWSER_BRIDGE_RPC_METHODS = [ enforcesExpectUrl: context.clientCapabilities?.includes(DESKTOP_BROWSER_BRIDGE_EXPECT_URL_CAPABILITY) ?? false, + readsTabAnnotations: + context.clientCapabilities?.includes(DESKTOP_BROWSER_BRIDGE_TAB_ANNOTATIONS_CAPABILITY) ?? + false, emit }) let release = (): void => {} diff --git a/src/main/runtime/rpc/methods/mobile-delivery/bundled-mobile-web-bundle.ts b/src/main/runtime/rpc/methods/mobile-delivery/bundled-mobile-web-bundle.ts index 62878b48a72..3cc62c1c7f9 100644 --- a/src/main/runtime/rpc/methods/mobile-delivery/bundled-mobile-web-bundle.ts +++ b/src/main/runtime/rpc/methods/mobile-delivery/bundled-mobile-web-bundle.ts @@ -1,8 +1,9 @@ -import { existsSync, readFileSync } from 'node:fs' +import { existsSync } from 'node:fs' +import { readFile } from 'node:fs/promises' import { join } from 'node:path' import { getAppEnvironment, hasAppEnvironment } from '../../../../../shared/app-environment' import { - MobileWebBundleManifestSchema, + InstalledMobileWebBundleManifestSchema, type MobileWebBundleManifest } from '../../../../../shared/mobile-web-bundle/manifest-contract' @@ -14,47 +15,63 @@ export type BundledMobileWebBundle = { } /** AppEnvironment keeps runtime imports Node-safe; absent environment means no install root. - * Probe app.asar/out and unpacked entrypoint layouts like getBundledWebClientRoot. */ + * Probe packaged and unpacked entrypoint layouts like findBundledWebClientRoot. */ export function getBundledMobileWebBundleRoot(): string | undefined { if (!hasAppEnvironment()) { return undefined } const appPath = getAppEnvironment().getAppPath() - const roots = [ - join(appPath, 'out', 'mobile-web'), - // Unpacked electron-vite sets appPath to out/main. - join(appPath, '..', 'mobile-web') - ] - return roots.find((root) => existsSync(join(root, MANIFEST_FILENAME))) -} - -// Installs are immutable until restart; undefined means unprobed, null means absent. -let cachedBundle: BundledMobileWebBundle | null | undefined - -export function loadBundledMobileWebBundle(): BundledMobileWebBundle | null { - if (cachedBundle === undefined) { - cachedBundle = readBundledMobileWebBundle() + if (probedRoot?.appPath === appPath) { + return probedRoot.root } - return cachedBundle + // Electron reads app.asar paths through the header it parsed at launch, which misses files an in-place update wrote. + const filesPath = appPath.endsWith('.asar') ? `${appPath}.unpacked` : appPath + const roots = [ + join(filesPath, 'out', 'mobile-web'), + // Unpacked electron-vite sets appPath to out/main. + join(filesPath, '..', 'mobile-web') + ] + const root = roots.find((candidate) => existsSync(join(candidate, MANIFEST_FILENAME))) + // An install keeps its layout, so only a miss is probed again (a dev build may produce the bundle later). + if (root) { + probedRoot = { appPath, root } + } + return root } -export function resetBundledMobileWebBundleCacheForTests(): void { - cachedBundle = undefined -} +let probedRoot: { appPath: string; root: string } | undefined -function readBundledMobileWebBundle(): BundledMobileWebBundle | null { +// Linux package managers replace the install under a running app, so the cache holds only while manifest.json's bytes do. +let cached: { root: string; raw: Buffer; bundle: BundledMobileWebBundle | null } | undefined + +export async function loadBundledMobileWebBundle(): Promise { const root = getBundledMobileWebBundleRoot() if (!root) { return null } const manifestPath = join(root, MANIFEST_FILENAME) - let raw: string + let raw: Buffer try { - raw = readFileSync(manifestPath, 'utf8') + raw = await readFile(manifestPath) } catch (error) { console.warn(`[mobile-web-bundle] cannot read ${manifestPath}:`, error) return null } + if (cached?.root !== root || !cached.raw.equals(raw)) { + cached = { + root, + raw, + bundle: parseBundledMobileWebBundle(root, manifestPath, raw.toString('utf8')) + } + } + return cached.bundle +} + +function parseBundledMobileWebBundle( + root: string, + manifestPath: string, + raw: string +): BundledMobileWebBundle | null { let parsed: unknown try { parsed = JSON.parse(raw) @@ -62,7 +79,7 @@ function readBundledMobileWebBundle(): BundledMobileWebBundle | null { console.warn(`[mobile-web-bundle] ${manifestPath} is not valid JSON:`, error) return null } - const manifest = MobileWebBundleManifestSchema.safeParse(parsed) + const manifest = InstalledMobileWebBundleManifestSchema.safeParse(parsed) if (!manifest.success) { // Bad dev/hand-edited bundles must degrade to absent, not crash a phone-accessible path. console.warn(`[mobile-web-bundle] ${manifestPath} does not match the manifest contract:`, { diff --git a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-asset-reader.ts b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-asset-reader.ts index e429c63e881..4d8167004a4 100644 --- a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-asset-reader.ts +++ b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-asset-reader.ts @@ -11,7 +11,7 @@ export function resetMobileWebBundleAssetVerdictsForTests(): void { verdicts.clear() } -/** Cache one asset hash verdict per build; store the pending promise before await so concurrent readers share the hash. */ +/** Cache one passing asset hash verdict per build; store the pending promise before await so concurrent readers share the hash. */ export function verifyMobileWebBundleAsset( root: string, buildId: string, @@ -22,11 +22,16 @@ export function verifyMobileWebBundleAsset( if (cached) { return cached } - const verdict = hashAsset(root, asset).then(undefined, (error: unknown) => { - // A read that failed is not evidence the bytes changed, so it is not remembered as a verdict. - verdicts.delete(key) - throw error - }) + const verdict = hashAsset(root, asset) + // Keep only a match: a package install may still be writing this build's files, and a failed read proves nothing. + void verdict.then( + (matches) => { + if (!matches) { + verdicts.delete(key) + } + }, + () => verdicts.delete(key) + ) verdicts.set(key, verdict) return verdict } diff --git a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-range.test.ts b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-range.test.ts index 5553b263030..ec3cab87d4d 100644 --- a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-range.test.ts +++ b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-range.test.ts @@ -13,8 +13,6 @@ import { type MobileWebBundleRangeResult } from '../../../../../shared/mobile-web-bundle/bundle-rpc-contract' -import { resetBundledMobileWebBundleCacheForTests } from './bundled-mobile-web-bundle' - import type { RpcResponse } from '../../core' import type { RpcDispatcher } from '../../dispatcher' @@ -66,7 +64,6 @@ const INCOMPRESSIBLE: SyntheticAsset = (() => { beforeEach(() => { scratch = mkdtempSync(join(tmpdir(), 'orca-mobile-web-bundle-range-')) installMobileWebBundleAppPath(scratch) - resetBundledMobileWebBundleCacheForTests() resetMobileWebBundleAssetVerdictsForTests() resetMobileWebBundleReadAdmissionForTests() vi.spyOn(console, 'warn').mockImplementation(() => {}) diff --git a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-window-refusals.test.ts b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-window-refusals.test.ts index e4ffbf35e4b..33ee1e2c731 100644 --- a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-window-refusals.test.ts +++ b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-window-refusals.test.ts @@ -7,7 +7,6 @@ import { MOBILE_WEB_BUNDLE_CHUNK_METHOD, MOBILE_WEB_BUNDLE_RANGE_METHOD } from '../../../../../shared/mobile-web-bundle/bundle-rpc-contract' -import { resetBundledMobileWebBundleCacheForTests } from './bundled-mobile-web-bundle' import type { RpcResponse } from '../../core' import type { RpcDispatcher } from '../../dispatcher' import { resetMobileWebBundleAssetVerdictsForTests } from './mobile-web-bundle-asset-reader' @@ -32,7 +31,6 @@ function errorMessage(response: RpcResponse): string | undefined { beforeEach(() => { scratch = mkdtempSync(join(tmpdir(), 'orca-mobile-web-bundle-window-')) installMobileWebBundleAppPath(scratch) - resetBundledMobileWebBundleCacheForTests() resetMobileWebBundleAssetVerdictsForTests() resetMobileWebBundleReadAdmissionForTests() vi.spyOn(console, 'warn').mockImplementation(() => {}) diff --git a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.test.ts b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.test.ts index 4ad687cb8f2..71549b9a859 100644 --- a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.test.ts +++ b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.test.ts @@ -1,4 +1,12 @@ -import { mkdirSync, mkdtempSync, rmSync, truncateSync, unlinkSync, writeFileSync } from 'node:fs' +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + truncateSync, + unlinkSync, + writeFileSync +} from 'node:fs' import { tmpdir } from 'node:os' @@ -18,8 +26,6 @@ import type { RpcRequest, RpcResponse } from '../../core' import '../../../../../shared/orcad-artifacts' import type { RpcDispatcher } from '../../dispatcher' -import { resetBundledMobileWebBundleCacheForTests } from './bundled-mobile-web-bundle' - import { fillMobileWebBundleReadWindow, resetMobileWebBundleAssetVerdictsForTests @@ -85,7 +91,6 @@ async function download(buildId: string, path: string): Promise<{ bytes: Buffer; beforeEach(() => { scratch = mkdtempSync(join(tmpdir(), 'orca-mobile-web-bundle-')) installMobileWebBundleAppPath(scratch) - resetBundledMobileWebBundleCacheForTests() resetMobileWebBundleAssetVerdictsForTests() resetMobileWebBundleReadAdmissionForTests() vi.spyOn(console, 'warn').mockImplementation(() => {}) @@ -140,19 +145,43 @@ describe('an install that carries a mobile web bundle', () => { expect(body).toMatchObject({ dataBase64: '', eof: true, assetByteLength: 0 }) }) - // After auto-update, report build-changed before path lookup so clients restart from the manifest. - it('refuses the old buildId after the install swaps bundles mid-download', async () => { + // Linux package managers replace the install under a running host (STA-14385): serve the new build, never the gone one. + it('serves the replacement build after the install swaps bundles under a running host', async () => { const script = bundle.assets.find((asset) => asset.path.endsWith('.js'))! + expect((await call('mobileWeb.bundle.manifest')).ok).toBe(true) expect((await chunk({ buildId: bundle.buildId, path: script.path, offset: 0 })).ok).toBe(true) rmSync(join(scratch, 'out', 'mobile-web'), { recursive: true, force: true }) const replacement = writeSyntheticMobileWebBundle(join(scratch, 'out', 'mobile-web'), 2) - resetBundledMobileWebBundleCacheForTests() expect(replacement.buildId).not.toBe(bundle.buildId) const stale = await chunk({ buildId: bundle.buildId, path: script.path, offset: 0 }) + const manifest = await call('mobileWeb.bundle.manifest') + const fresh = await chunk({ buildId: replacement.buildId, path: 'index.html', offset: 0 }) expect(errorMessage(stale)).toBe('mobile_web_bundle_build_changed') + expect( + MobileWebBundleManifestResultSchema.parse(manifest.ok && manifest.result).manifest.buildId + ).toBe(replacement.buildId) + expect(errorMessage(fresh)).toBeUndefined() + }) + + // A newer release written in place may add schema-v1 fields this host predates; it serves only the ones it knows. + it('serves a replacement manifest that carries fields this host does not know', async () => { + rmSync(join(scratch, 'out', 'mobile-web'), { recursive: true, force: true }) + const replacement = writeSyntheticMobileWebBundle(join(scratch, 'out', 'mobile-web'), 5) + const manifestPath = join(replacement.root, 'manifest.json') + const written = JSON.parse(readFileSync(manifestPath, 'utf8')) + written.assets[0].laterAssetField = 1 + written.laterManifestField = true + writeFileSync(manifestPath, JSON.stringify(written), 'utf8') + + const response = await call('mobileWeb.bundle.manifest') + + const manifest = MobileWebBundleManifestResultSchema.parse( + response.ok && response.result + ).manifest + expect(manifest.buildId).toBe(replacement.buildId) }) // A path survives rebuild; key verdicts by build too so an old failure cannot poison new bytes. @@ -164,13 +193,26 @@ describe('an install that carries a mobile web bundle', () => { rmSync(join(scratch, 'out', 'mobile-web'), { recursive: true, force: true }) const replacement = writeSyntheticMobileWebBundle(join(scratch, 'out', 'mobile-web'), 8) - resetBundledMobileWebBundleCacheForTests() const response = await chunk({ buildId: replacement.buildId, path: 'index.html', offset: 0 }) expect(errorMessage(response)).toBeUndefined() }) + // A package install writes the manifest and assets one file at a time; a mismatch mid-install must not stick. + it('serves an asset once its bytes match again, after a mismatch for the same build', async () => { + const original = mobileWebBundleFiller(640, 3) + writeFileSync(join(bundle.root, 'index.html'), mobileWebBundleFiller(640, 99)) + expect( + errorMessage(await chunk({ buildId: bundle.buildId, path: 'index.html', offset: 0 })) + ).toBe('mobile_web_bundle_asset_changed') + + writeFileSync(join(bundle.root, 'index.html'), original) + const response = await chunk({ buildId: bundle.buildId, path: 'index.html', offset: 0 }) + + expect(errorMessage(response)).toBeUndefined() + }) + // Map post-verification filesystem failure to a contract code without exposing the host install path. it('answers a changed asset, not the filesystem error, when the asset is gone after its verdict', async () => { const script = bundle.assets.find((asset) => asset.path.endsWith('.js'))! @@ -259,7 +301,20 @@ describe('where the resolver probes', () => { it('finds the bundle beside an out/main app path', async () => { const bundle = writeSyntheticMobileWebBundle(join(scratch, 'out', 'mobile-web'), 3) installMobileWebBundleAppPath(join(scratch, 'out', 'main')) - resetBundledMobileWebBundleCacheForTests() + + const response = await call('mobileWeb.bundle.manifest') + + expect( + MobileWebBundleManifestResultSchema.parse(response.ok && response.result).manifest.buildId + ).toBe(bundle.buildId) + }) + + it('reads a packaged app from app.asar.unpacked, where an in-place update writes its files', async () => { + const bundle = writeSyntheticMobileWebBundle( + join(scratch, 'app.asar.unpacked', 'out', 'mobile-web'), + 4 + ) + installMobileWebBundleAppPath(join(scratch, 'app.asar')) const response = await call('mobileWeb.bundle.manifest') @@ -282,7 +337,6 @@ describe('an install with no mobile web bundle', () => { const root = join(scratch, 'out', 'mobile-web') mkdirSync(root, { recursive: true }) writeFileSync(join(root, 'manifest.json'), 'not json', 'utf8') - resetBundledMobileWebBundleCacheForTests() expect(errorMessage(await call('mobileWeb.bundle.manifest'))).toBe( 'mobile_web_bundle_unavailable' diff --git a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.ts b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.ts index c7fe1de157b..3f763acedca 100644 --- a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.ts +++ b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.ts @@ -50,8 +50,8 @@ function bundleError(code: MobileWebBundleErrorCode): InvalidArgumentError { return new InvalidArgumentError(code) } -function requireBundle(): BundledMobileWebBundle { - const bundle = loadBundledMobileWebBundle() +async function requireBundle(): Promise { + const bundle = await loadBundledMobileWebBundle() if (!bundle) { throw bundleError('mobile_web_bundle_unavailable') } @@ -69,7 +69,7 @@ async function readLocaleCatalog( params: MobileWebBundleLocaleCatalogParams, ctx: RpcContext ): Promise { - const bundle = requireBundle() + const bundle = await requireBundle() const entry = bundle.manifest.catalogs?.find((catalog) => catalog.locale === params.locale) if (!entry) { throw bundleError('mobile_web_bundle_asset_unknown') @@ -157,7 +157,7 @@ async function readVerifiedWindow( encode: (window: VerifiedWindow) => Promise, sourceOf: (asset: MobileWebBundleAsset) => WindowSource = (asset) => asset ): Promise { - const bundle = requireBundle() + const bundle = await requireBundle() // Check build before path: auto-update means restart from the manifest, not missing-asset. if (params.buildId !== bundle.manifest.buildId) { throw bundleError('mobile_web_bundle_build_changed') @@ -212,7 +212,7 @@ export const MOBILE_WEB_BUNDLE_METHODS = [ permission: 'workspace', params: null, handler: async (): Promise => ({ - manifest: requireBundle().manifest, + manifest: (await requireBundle()).manifest, chunkBytes: MOBILE_WEB_BUNDLE_CHUNK_BYTES, // Complete replies must arrive within the phone's stall budget even on slow relays. rangeBytes: MOBILE_WEB_BUNDLE_CHUNK_BYTES diff --git a/src/main/runtime/rpc/methods/orchestration/access/orchestration-access-outcomes.test.ts b/src/main/runtime/rpc/methods/orchestration/access/orchestration-access-outcomes.test.ts index 0165250f962..694ff102ae1 100644 --- a/src/main/runtime/rpc/methods/orchestration/access/orchestration-access-outcomes.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/access/orchestration-access-outcomes.test.ts @@ -223,6 +223,7 @@ const CASES = { }) }, peerMailPull: { method: 'orchestration.peerMailPull', params: () => ({ waitMs: 0 }) }, + peerRunCancel: { method: 'orchestration.peerRunCancel', params: () => ({}) }, replyHelperQuestion: { method: 'orchestration.reply', params: (from, ids) => ({ id: ids.helperQuestion, body: 'a', from }) @@ -376,6 +377,7 @@ const EXPECTED: Record & Record = { 'mail_requires_server_pairing mail_requires_server_pairing mail_requires_server_pairing mail_requires_server_pairing', peerMailPull: 'mail_requires_server_pairing mail_requires_server_pairing mail_requires_server_pairing mail_requires_server_pairing', + peerRunCancel: 'forbidden forbidden forbidden forbidden', replyHelperQuestion: 'ok consumer_fenced consumer_fenced ok', replyMail: 'ok ok ok ok', replyQuestion: 'ok consumer_fenced consumer_fenced worker_cannot_coordinate_own_run', diff --git a/src/main/runtime/rpc/methods/orchestration/access/orchestration-method-access.ts b/src/main/runtime/rpc/methods/orchestration/access/orchestration-method-access.ts index 01c58ffda86..c36f9dd7336 100644 --- a/src/main/runtime/rpc/methods/orchestration/access/orchestration-method-access.ts +++ b/src/main/runtime/rpc/methods/orchestration/access/orchestration-method-access.ts @@ -3,6 +3,11 @@ import { types } from 'node:util' import type { ZodType } from 'zod' import type { RpcContext, RpcTypedMethod, RpcTypedStreamingMethod } from '../../../core' +import { + checkPeerAccess, + refusePeerAddressClaim, + refuseServerCallFromPeerRun +} from './peer-run-access' type ParsedParams = TSchema extends ZodType ? TSchema['_output'] @@ -28,6 +33,9 @@ export type OrchestrationSubjectKind = /** A field naming who is calling, as opposed to what the call acts on. */ export type OrchestrationCallerField = 'from' | 'terminal' | 'callerTerminalHandle' +/** The pane key a caller sends with its caller field, which only its own host can fill. */ +export type OrchestrationCallerPaneField = 'terminalPaneKey' | 'senderPaneKey' + type FieldOf

= P extends object ? Extract : never export type OrchestrationAccessRuleInput

= { @@ -43,6 +51,9 @@ export type OrchestrationAccessRule = (input: OrchestrationAccessRuleInput export type OrchestrationMethodAccess = { readonly kind: OrchestrationAccessKind readonly caller?: Extract, OrchestrationCallerField> + readonly callerPane?: Extract, OrchestrationCallerPaneField> + /** The field that sends the call on to a paired server (`--on`). */ + readonly server?: Extract, 'on'> /** Every field naming something the call acts on, kept apart from the caller field. */ readonly targets: Readonly, OrchestrationSubjectKind>>> /** A read returning a collection; a narrower caller restricts its query, never its page. */ @@ -54,32 +65,55 @@ export type OrchestrationMethodAccess = { export type OrchestrationMethodAccessDeclaration = { readonly kind: OrchestrationAccessKind readonly caller?: OrchestrationCallerField + readonly callerPane?: OrchestrationCallerPaneField + readonly server?: 'on' readonly targets: Readonly>> readonly collection?: true readonly rule?: OrchestrationAccessRule } -/** The one access check: every caller on this Orca is held to the method's own rule. */ +/** The one access check: every caller on this Orca is held to the method's own rule, and a paired + * Orca also to the Run it coordinates here. Returns the params the method runs with and its grant. */ export function checkOrchestrationAccess( access: OrchestrationMethodAccess, params: P, ctx: RpcContext -): G { +): { params: P; grant: G } { + const caller = ctx.orchestrationCaller + if (caller?.kind !== 'peer') { + refusePeerAddressClaim(access.caller && fieldValue(access.caller, params)) + refusePeerAddressClaim(access.callerPane && fieldValue(access.callerPane, params)) + } + const scoped = + caller?.kind === 'peer' + ? checkPeerAccess(access, params, ctx.runtime.getOrchestrationDb(), caller) + : params + if (access.server && fieldValue(access.server, scoped) !== undefined) { + refuseServerCallFromPeerRun(ctx, declaredCaller(access.caller, scoped)) + } if (!access.rule) { // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: G defaults to undefined exactly when a method declares no rule. - return undefined as G + return { params: scoped, grant: undefined as G } + } + return { + params: scoped, + grant: access.rule({ params: scoped, ctx, caller: declaredCaller(access.caller, scoped) }) } - return access.rule({ params, ctx, caller: declaredCaller(access.caller, params) }) } function declaredCaller

( field: Extract, OrchestrationCallerField> | undefined, params: P ): string | undefined { - if (field === undefined) { - return undefined - } - const value: unknown = params[field] + return field === undefined ? undefined : fieldValue(field, params) +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null +} + +function fieldValue(field: string, params: unknown): string | undefined { + const value: unknown = isRecord(params) ? params[field] : undefined return typeof value === 'string' ? value : undefined } @@ -154,7 +188,8 @@ export function defineOrchestrationMethod< // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a replay returns the receipt this handler produced when the call was accepted; a promise-returning handler's wrapper is async. return replayed.receipt as TResult } - return handler(params, ctx, checkOrchestrationAccess(access, params, ctx)) + const checked = checkOrchestrationAccess(access, params, ctx) + return handler(checked.params, ctx, checked.grant) }) } } @@ -191,8 +226,10 @@ export function defineOrchestrationStreamingMethod< handler: checked( handler, declaration, - (params: ParsedParams, ctx: RpcContext, emit: (result: unknown) => void) => - handler(params, ctx, emit, checkOrchestrationAccess(access, params, ctx)) + (params: ParsedParams, ctx: RpcContext, emit: (result: unknown) => void) => { + const checked = checkOrchestrationAccess(access, params, ctx) + return handler(checked.params, ctx, emit, checked.grant) + } ) } } diff --git a/src/main/runtime/rpc/methods/orchestration/access/peer-run-access.ts b/src/main/runtime/rpc/methods/orchestration/access/peer-run-access.ts new file mode 100644 index 00000000000..6755ba30dbb --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/access/peer-run-access.ts @@ -0,0 +1,208 @@ +import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import { + isPeerCoordinatorAddress, + type OrchestrationPeerCaller +} from '../../../../orchestration/addressing/orchestration-caller-identity' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import { parseOrcaSessionAddress } from '../../../../../../shared/orca-session-address' +import type { RpcContext } from '../../../core' +import { resolveDispatchCreator } from '../runs/dispatch-creator' +import type { + OrchestrationMethodAccessDeclaration, + OrchestrationSubjectKind +} from './orchestration-method-access' + +const NO_EFFECTS = { effectsApplied: false } as const + +/** Kinds named by an ID: one this Orca does not have is in no Run, and the method answers it as + * not found. Addresses also name terminals and sessions that work in no Run, so they must resolve. */ +const ID_KINDS: ReadonlySet = new Set([ + 'dispatch', + 'task', + 'message', + 'gate' +]) + +/** + * A paired Orca acts only inside the Run it coordinates here: every subject a call names must be in + * that Run, and a collection read is narrowed to it before its query runs, so counts and cursors + * stay right. Calls that act on this Orca as a whole are this Orca's own. Returns the params the + * method runs with. + */ +export function checkPeerAccess

( + access: OrchestrationMethodAccessDeclaration, + params: P, + db: OrchestrationDb, + peer: OrchestrationPeerCaller +): P { + const { run_id: runId, home_label: label } = peer.peerRun + if (access.kind === 'localOnly') { + throw new OrchestrationError( + 'forbidden', + `This command acts on this server as a whole, so only this server can run it, not ${label}. No effects were applied.`, + NO_EFFECTS + ) + } + const values: Record = + params && typeof params === 'object' ? { ...(params as Record) } : {} + for (const [field, kind] of Object.entries(access.targets)) { + for (const subject of subjectsOf(values[field])) { + const subjectRunId = kind && resolveSubjectRunId(db, kind, subject, peer) + if (kind && subjectRunId !== runId && !(subjectRunId === undefined && ID_KINDS.has(kind))) { + throw new OrchestrationError( + 'forbidden', + `${subject} is not in the Run ${label} coordinates here. No effects were applied.`, + NO_EFFECTS + ) + } + } + } + if (access.collection) { + const runField = Object.entries(access.targets).find(([, kind]) => kind === 'run')?.[0] + if (!runField) { + throw new OrchestrationError( + 'forbidden', + `This list spans every Run on this server, so ${label} cannot read it. No effects were applied.`, + NO_EFFECTS + ) + } + values[runField] = runId + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the same params with at most the declared Run field set to a string, which every Run field accepts. + return (params && typeof params === 'object' ? values : params) as P +} + +function subjectsOf(value: unknown): string[] { + if (Array.isArray(value)) { + return value.filter((item): item is string => typeof item === 'string') + } + if (typeof value !== 'string' || value === '') { + return [] + } + if (!value.startsWith('[') && !value.startsWith('{')) { + return [value] + } + // A JSON list of IDs (`--deps`), or send's JSON payload, which names its Dispatch by `dispatchId`. + let parsed: unknown + try { + parsed = JSON.parse(value) + } catch { + return [value] + } + if (Array.isArray(parsed)) { + return subjectsOf(parsed) + } + const dispatchId = + parsed && typeof parsed === 'object' && 'dispatchId' in parsed ? parsed.dispatchId : undefined + return typeof dispatchId === 'string' ? [dispatchId] : [] +} + +/** The Run a subject belongs to on this Orca, or undefined when it names nothing here. */ +export function resolveSubjectRunId( + db: OrchestrationDb, + kind: OrchestrationSubjectKind, + subject: string, + peer: OrchestrationPeerCaller +): string | undefined { + switch (kind) { + case 'run': + return subject + case 'dispatch': + return db.getDispatchContextById(subject)?.run_id + case 'task': + return db.getTask(subject)?.run_id + case 'message': + return db.getMessageById(subject)?.run_id + case 'gate': + return db.getGate(subject)?.run_id + case 'request': + // Receipts are keyed by the pairing, so they are its own; the same paired Orca may read another of its Runs' receipts. + return peer.peerRun.run_id + case 'worker': + case 'session': + return assigneeRunId(db, subject) + case 'party': + return partyRunId(db, subject, peer) + case 'conversation': + return undefined + } +} + +function partyRunId( + db: OrchestrationDb, + address: string, + peer: OrchestrationPeerCaller +): string | undefined { + if (address === peer.address) { + return peer.peerRun.run_id + } + if (address.startsWith('run:')) { + return address.slice('run:'.length) + } + if (address.startsWith('dispatch:')) { + return db.getDispatchContextById(address.slice('dispatch:'.length))?.run_id + } + // A group spans Runs, so it never resolves into one. + return address.startsWith('@') ? undefined : assigneeRunId(db, address) +} + +/** The Run of the newest Dispatch a terminal, pane or session was given. */ +function assigneeRunId(db: OrchestrationDb, subject: string): string | undefined { + const session = parseOrcaSessionAddress(subject) ?? subject + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT of one column returns exactly that column. + const row = db.db + .prepare( + `SELECT run_id FROM dispatch_contexts + WHERE assignee_handle = ?1 OR assignee_pane_key = ?1 OR assignee_orca_session_id = ?2 + ORDER BY rowid DESC LIMIT 1` + ) + .get(subject, session) as { run_id: string } | undefined + return row?.run_id +} + +/** Only a paired Orca's own frames speak as it: its address is predictable, so no other caller may + * declare it as its handle or pane and read or bind its Run's mail. */ +export function refusePeerAddressClaim(declared: string | undefined): void { + if (isPeerCoordinatorAddress(declared)) { + throw new OrchestrationError( + 'forbidden', + `${declared} is a paired Orca's coordinator address, and only that Orca can act as it. No effects were applied.`, + NO_EFFECTS + ) + } +} + +/** Pairing is one-way: work running in a paired Orca's Run, its helpers' included, never calls on + * to another server, and neither does that Orca through this one. */ +export function refuseServerCallFromPeerRun( + ctx: RpcContext, + callerHandle: string | undefined +): void { + const db = ctx.runtime.getOrchestrationDb() + const caller = ctx.orchestrationCaller + // Most servers coordinate no paired Orca's Run, and then the creator lookup (which can refuse) is skipped. + const peerRun = + caller?.kind === 'peer' + ? caller.peerRun + : db.hasPeerRuns() + ? peerRunOfCallerWork(ctx, db, callerHandle) + : undefined + if (peerRun) { + throw new OrchestrationError( + 'forbidden', + `This work is coordinated from ${peerRun.home_label}, so it cannot use --on. Ask that coordinator instead. No effects were applied.`, + NO_EFFECTS + ) + } +} + +function peerRunOfCallerWork( + ctx: RpcContext, + db: OrchestrationDb, + callerHandle: string | undefined +): ReturnType { + const creator = resolveDispatchCreator(ctx.runtime, callerHandle, ctx.orchestrationCaller) + const dispatchId = db.resolveCreatorDispatchId(creator) + const runId = dispatchId ? db.getDispatchContextById(dispatchId)?.run_id : undefined + return runId ? db.getPeerRun(runId) : undefined +} diff --git a/src/main/runtime/rpc/methods/orchestration/caller-show.ts b/src/main/runtime/rpc/methods/orchestration/caller-show.ts index 9ee58a20e4d..5d0acbef31b 100644 --- a/src/main/runtime/rpc/methods/orchestration/caller-show.ts +++ b/src/main/runtime/rpc/methods/orchestration/caller-show.ts @@ -75,9 +75,13 @@ export const ORCHESTRATION_CALLER_METHODS = [ _params, { orchestrationCaller, orchestrationCompatibilityEvidence, runtime } ): OrchestrationCallerShowResult => ({ - caller: orchestrationCaller - ? { orcaSessionId: formatOrcaSessionAddress(orchestrationCaller.orcaSessionId), live: true } - : null, + caller: + orchestrationCaller && orchestrationCaller.kind !== 'peer' + ? { + orcaSessionId: formatOrcaSessionAddress(orchestrationCaller.orcaSessionId), + live: true + } + : null, // An Orca-launched agent's own pane and launch secret prove it is one; no hook needs to have fired. terminal: !orchestrationCaller && diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts index c0e0e2f50a8..5d4c9640030 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts @@ -4,10 +4,12 @@ import { ORCHESTRATION_FEDERATION_RELAY_METHODS } from '../../../../orchestration/legacy-remote/legacy-remote' import { ORCHESTRATION_PEER_MAIL_METHODS } from './peer-mail-methods' +import { ORCHESTRATION_PEER_RUN_METHODS } from './peer-run-methods' export const ORCHESTRATION_FEDERATION_METHODS = [ ...ORCHESTRATION_FEDERATION_ATTACH_METHODS, ...ORCHESTRATION_FEDERATION_RELAY_METHODS, ...ORCHESTRATION_FEDERATION_CONTROL_METHODS, - ...ORCHESTRATION_PEER_MAIL_METHODS + ...ORCHESTRATION_PEER_MAIL_METHODS, + ...ORCHESTRATION_PEER_RUN_METHODS ] diff --git a/src/main/runtime/rpc/methods/orchestration/federation/peer-coordinator.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/peer-coordinator.test.ts new file mode 100644 index 00000000000..8d06f4d4123 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/federation/peer-coordinator.test.ts @@ -0,0 +1,437 @@ +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 { generateId } from '../../../../orchestration/db/generated-id' +import { createRootDispatch } from '../../../../orchestration/db/root-dispatch-test-fixture' +import { RpcDispatcher } from '../../../dispatcher' +import type { RpcResponse } from '../../../core' +import { ORCHESTRATION_METHODS } from '../orchestration' +import { startWorker } from '../worker/workers' +import { peerCoordinatorCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' + +const WORKER_PANE = 'tab_w:11111111-1111-4111-8111-111111111111' +const OTHER_PANE = 'tab_o:22222222-2222-4222-8222-222222222222' +const LOCAL_PANE = 'tab_l:33333333-3333-4333-8333-333333333333' +const PAIRED = { + authenticatedCallerFingerprint: 'fingerprint_a', + pairedDeviceId: 'device_a', + clientKind: 'runtime' as const +} + +describe('a paired Orca coordinating its Run on this server', () => { + let dir: string + let db: OrchestrationDb + let runtime: OrcaRuntimeService + let dispatcher: RpcDispatcher + let conversationId: string + let sequence = 0 + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'orca-peer-coordinator-')) + db = new OrchestrationDb(join(dir, 'b.db')) + runtime = new OrcaRuntimeService(null) + const panes: Record = { + term_w: WORKER_PANE, + term_o: OTHER_PANE, + term_l: LOCAL_PANE + } + vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => panes[handle] ?? null) + vi.spyOn(runtime, 'getLiveTerminalPaneKey').mockImplementation( + (handle) => panes[handle] ?? null + ) + runtime.setOrchestrationDb(db) + dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) + conversationId = generateId('peerconv') + }) + + afterEach(() => { + db.close() + rmSync(dir, { recursive: true, force: true }) + vi.restoreAllMocks() + vi.useRealTimers() + }) + + function peerCall( + method: string, + params: Record, + options: { requestId?: string; conversation?: string } = {} + ): Promise { + sequence += 1 + return dispatcher.dispatch( + { + id: `peer_${sequence}`, + authToken: 'token', + method, + params, + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, + orchestrationPeerRun: { + runId: 'run_home', + conversationId: options.conversation ?? conversationId, + label: 'devA' + }, + ...(options.requestId ? { orchestrationRequestId: options.requestId } : {}) + }, + PAIRED + ) + } + + function localCall(method: string, params: Record): Promise { + sequence += 1 + return dispatcher.dispatch({ + id: `local_${sequence}`, + authToken: 'token', + method, + params, + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION + }) + } + + function peerRunId(): string { + return db.getPeerRunForConversation(conversationId)!.run_id + } + + /** The peer's Run with one worker in it, and a local Run with another. */ + async function twoRuns() { + await peerCall('orchestration.runCurrent', {}) + const peerTask = db.createTask({ spec: 'peer work', runId: peerRunId() }) + const peerWork = createRootDispatch(db, peerTask.id, 'term_w', WORKER_PANE) + const localRun = db.createRun({ + objective: 'local', + coordinatorHandle: 'term_l', + coordinatorPaneKey: LOCAL_PANE + }) + const localTask = db.createTask({ spec: 'local work', runId: localRun.id }) + const localWork = createRootDispatch(db, localTask.id, 'term_o', OTHER_PANE) + return { peerWork, localRun, localWork } + } + + async function pull(id: string, params: Record = {}) { + const response = await dispatcher.dispatch( + { + id, + authToken: 'token', + method: 'orchestration.peerMailPull', + params, + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION + }, + PAIRED + ) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the pull's result schema; a refusal reads as an empty page. + return (response.ok ? response.result : { items: [] }) as { + items: { conversationId: string; kind: string }[] + } + } + + function refused(response: RpcResponse): string | undefined { + return response.ok ? undefined : response.error.code + } + + it("writes the peer's Run when its frame arrives, before the call awaits anything", () => { + const pending = peerCall('orchestration.runCurrent', {}) + const run = db.getPeerRunForConversation(conversationId) + expect(run).toMatchObject({ home_run_id: 'run_home', home_label: 'devA', state: 'open' }) + expect(db.getRun(run!.run_id)).toBeDefined() + return pending + }) + + it('admits a peer Run only from a runtime pairing', async () => { + sequence += 1 + const response = await dispatcher.dispatch( + { + id: 'mobile', + authToken: 'token', + method: 'orchestration.runCurrent', + params: {}, + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, + orchestrationPeerRun: { runId: 'run_home', conversationId, label: 'devA' } + }, + { ...PAIRED, clientKind: 'mobile' } + ) + expect(refused(response)).toBe('mail_requires_server_pairing') + expect(db.getPeerRunForConversation(conversationId)).toBeUndefined() + }) + + it('refuses commands that act on this server as a whole', async () => { + const { localRun } = await twoRuns() + expect(refused(await peerCall('orchestration.reset', { all: true }))).toBe('forbidden') + expect(refused(await peerCall('orchestration.runUse', { id: localRun.id }))).toBe('forbidden') + expect(db.getRun(localRun.id)).toBeDefined() + }) + + it("keeps another Run's worker out of reach by terminal, pane or session, but not its own", async () => { + const { peerWork, localWork } = await twoRuns() + db.db + .prepare('UPDATE dispatch_contexts SET assignee_orca_session_id = ? WHERE id = ?') + .run('33333333-3333-4333-8333-333333333334', localWork.id) + + for (const target of [ + { terminal: 'term_o' }, + { paneKey: OTHER_PANE }, + { sessionId: '33333333-3333-4333-8333-333333333334' } + ]) { + expect( + refused(await peerCall('orchestration.workerKeepOpen', { ...target, keep: true })) + ).toBe('forbidden') + } + expect(peerWork.assignee_handle).toBe('term_w') + expect( + (await peerCall('orchestration.workerKeepOpen', { terminal: 'term_w', keep: true })).ok + ).toBe(true) + }) + + it('reads only its own Run from an unqualified worker list and inbox', async () => { + const { peerWork, localRun } = await twoRuns() + db.insertMessage({ + from: 'term_w', + to: `run:${peerRunId()}`, + subject: 'mine', + runId: peerRunId() + }) + db.insertMessage({ + from: 'term_o', + to: `run:${localRun.id}`, + subject: 'theirs', + runId: localRun.id + }) + + const list = await peerCall('orchestration.workerList', { paginate: true }) + const inbox = await peerCall('orchestration.inbox', {}) + + expect(list.ok && list.result).toMatchObject({ + workers: [{ dispatchId: peerWork.id, coordinatedFrom: 'devA' }], + page: { total: 1 } + }) + expect(inbox.ok && inbox.result).toMatchObject({ messages: [{ subject: 'mine' }], count: 1 }) + }) + + it('sends and replies only inside its own Run, by any address form', async () => { + const { localRun, localWork } = await twoRuns() + const question = db.insertMessage({ + from: 'term_o', + to: `run:${localRun.id}`, + subject: 'Question', + type: 'question', + runId: localRun.id + }) + for (const to of ['term_o', `dispatch:${localWork.id}`, `run:${localRun.id}`, '@all']) { + expect(refused(await peerCall('orchestration.send', { to, subject: 'hi' }))).toBe('forbidden') + } + expect(refused(await peerCall('orchestration.reply', { id: question.id, body: 'yes' }))).toBe( + 'forbidden' + ) + }) + + it('cannot reach its former worker once that terminal coordinates local work', async () => { + await twoRuns() + db.createRun({ + objective: 'later local', + coordinatorHandle: 'term_w', + coordinatorPaneKey: WORKER_PANE + }) + expect(refused(await peerCall('orchestration.send', { to: 'term_w', subject: 'hi' }))).toBe( + 'forbidden' + ) + }) + + it('refuses a start that would place in its workspace, which it has none of here', async () => { + for (const worktree of ['current', 'new-child']) { + const response = await peerCall('orchestration.workerStart', { spec: 'work', worktree }) + expect(response.ok ? undefined : response.error).toMatchObject({ + code: 'invalid_argument', + message: expect.stringContaining('--on requires an exact remote worktree selector') + }) + } + }) + + it('follows up with a finished worker where that worker ran, though it has no workspace here', async () => { + await peerCall('orchestration.runCurrent', {}) + const peer = peerCoordinatorCaller(db.getPeerRunForConversation(conversationId)!) + const placed = startWorker( + { from: peer.address, run: peerRunId(), spec: 'One more thing' }, + { + runtime, + orchestrationMutation: undefined, + orchestrationCompatibilityEvidence: undefined, + orchestrationCaller: peer + }, + { + of: 'ctx_finished', + addressed: 'ctx_finished', + place: async () => { + throw new Error('placed where the worker ran') + } + } + ) + await expect(placed).rejects.toThrow('placed where the worker ran') + }) + + it("never answers one Run's cancel with another Run's receipt", async () => { + const other = generateId('peerconv') + await peerCall('orchestration.peerRunCancel', {}, { requestId: 'cancel:1.1' }) + const second = await peerCall( + 'orchestration.peerRunCancel', + {}, + { requestId: 'cancel:1.1', conversation: other } + ) + expect(second.ok && second.result).not.toMatchObject({ mutation: { replayed: true } }) + }) + + it('stays the only coordinator of its Run: a local terminal cannot bind it', async () => { + await twoRuns() + const response = await localCall('orchestration.runUse', { id: peerRunId(), from: 'term_l' }) + expect(refused(response)).toBe('consumer_fenced') + expect(db.getRun(peerRunId())?.coordinator_handle).toBe(`peer:${conversationId}`) + }) + + it('cannot be impersonated by a local caller declaring its address', async () => { + await twoRuns() + const address = `peer:${conversationId}` + const mail = db.insertMessage({ + from: 'term_w', + to: address, + subject: 'done', + runId: peerRunId() + }) + const check = await localCall('orchestration.check', { + terminal: address, + terminalPaneKey: address + }) + expect(refused(check)).toBe('forbidden') + expect(db.getMessageById(mail.id)?.read).toBe(0) + const send = await localCall('orchestration.send', { + from: 'term_l', + senderPaneKey: address, + to: 'term_w', + subject: 'hi' + }) + expect(refused(send)).toBe('forbidden') + }) + + it('keeps work in its Run, helpers included, from calling on to another server', async () => { + const { localRun } = await twoRuns() + const helperTask = db.createTask({ spec: 'helper', runId: peerRunId() }) + createRootDispatch(db, helperTask.id, 'term_l', LOCAL_PANE) + for (const [method, params] of [ + ['orchestration.send', { from: 'term_w', to: 'term_x', subject: 'hi', on: 'devC' }], + ['orchestration.workerStart', { from: 'term_l', spec: 'more', on: 'devC' }] + ] as const) { + const response = await localCall(method, params) + expect(response.ok ? undefined : response.error.message).toMatch(/coordinated from devA/) + } + expect(localRun.id).toBeDefined() + }) + + it('cancels over the ordinary stop and answers what it could not yet prove stopped', async () => { + await peerCall('orchestration.runCurrent', {}) + const task = db.createTask({ spec: 'peer work', runId: peerRunId() }) + const { dispatch } = db.createStartingWorkerDispatch({ + taskId: task.id, + startOptions: {}, + creator: { kind: 'system' }, + maxDepth: 5 + }) + const remaining = async (requestId: string) => { + const response = await peerCall('orchestration.peerRunCancel', {}, { requestId }) + return response.ok ? response.result : response.error + } + + // A worker still starting cannot be stopped yet, so the cancel is owed again. + expect(await remaining('cancel:1.1')).toMatchObject({ remaining: 1 }) + expect(db.getPeerRunForConversation(conversationId)?.state).toBe('closed') + db.transitionLifecycle({ entity: 'worker', id: dispatch.id, from: 'starting', to: 'failed' }) + // A lost answer's retry replays it; a new attempt runs the stops again. + expect(await remaining('cancel:1.1')).toMatchObject({ + remaining: 1, + mutation: { replayed: true } + }) + expect(await remaining('cancel:1.2')).toMatchObject({ remaining: 0 }) + }) + + it('cancels a Run it never had, and closes it', async () => { + const response = await peerCall('orchestration.peerRunCancel', {}, { requestId: 'cancel:1.1' }) + expect(response.ok && response.result).toMatchObject({ remaining: 0 }) + expect(db.getPeerRunForConversation(conversationId)?.state).toBe('closed') + // A closed Run still admits its coordinator's cancel. + const again = await peerCall('orchestration.peerRunCancel', {}, { requestId: 'cancel:1.2' }) + expect(again.ok && again.result).toMatchObject({ remaining: 0 }) + }) + + it('gives every conversation a share of each pull, so an unimportable head starves no other', async () => { + const stuck = conversationId + const other = generateId('peerconv') + await peerCall('orchestration.runCurrent', {}) + await peerCall('orchestration.runCurrent', {}, { conversation: other }) + const stuckRun = db.getPeerRunForConversation(stuck)!.run_id + const otherRun = db.getPeerRunForConversation(other)!.run_id + for (let index = 0; index < 60; index += 1) { + db.insertMessage({ + from: 'term_w', + to: `run:${stuckRun}`, + subject: `s${index}`, + runId: stuckRun + }) + } + db.insertMessage({ from: 'term_w', to: `run:${otherRun}`, subject: 'done', runId: otherRun }) + + const items = await pull('pull') + expect(items.items.filter((item) => item.conversationId === other)).toEqual([ + expect.objectContaining({ kind: 'worker_mail' }) + ]) + }) + + it('fits every pending conversation in one page when they number fewer than its size', async () => { + const conversations = Array.from({ length: 30 }, () => generateId('peerconv')) + for (const conversation of conversations) { + await peerCall('orchestration.runCurrent', {}, { conversation }) + const runId = db.getPeerRunForConversation(conversation)!.run_id + for (const subject of ['one', 'two']) { + db.insertMessage({ from: 'term_w', to: `run:${runId}`, subject, runId }) + } + } + const page = await pull('pull') + expect(new Set(page.items.map((item) => item.conversationId)).size).toBe(30) + }) + + it('rotates the page when more conversations are pending than it holds, so none starves', async () => { + const conversations = Array.from({ length: 51 }, () => generateId('peerconv')) + for (const conversation of conversations) { + await peerCall('orchestration.runCurrent', {}, { conversation }) + const runId = db.getPeerRunForConversation(conversation)!.run_id + db.insertMessage({ from: 'term_w', to: `run:${runId}`, subject: 'stuck', runId }) + } + const seen = new Set() + for (const id of ['pull_1', 'pull_2']) { + for (const item of (await pull(id)).items) { + seen.add(item.conversationId) + } + } + expect(seen.size).toBe(51) + }) + + it('wakes a waiting pull when a worker in its Run changes state', async () => { + await peerCall('orchestration.runCurrent', {}) + const task = db.createTask({ spec: 'peer work', runId: peerRunId() }) + const { dispatch } = db.createStartingWorkerDispatch({ + taskId: task.id, + startOptions: {}, + creator: { kind: 'system' }, + maxDepth: 5 + }) + db.acknowledgeFederationRelay({ + dispatchId: conversationId, + direction: 'to_home', + throughSequence: 1_000 + }) + // The pull's own deadline never passes, so only the state change can answer it. + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + const waiting = pull('pull', { waitMs: 20_000 }) + await new Promise((resolve) => setImmediate(resolve)) + db.transitionLifecycle({ entity: 'worker', id: dispatch.id, from: 'starting', to: 'ready' }) + + expect((await waiting).items).toEqual([expect.objectContaining({ kind: 'worker_state' })]) + }) +}) 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 6d79a0577dd..7c7b5df0a94 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 @@ -35,17 +35,24 @@ function requireRuntimePairing( return ctx.authenticatedCallerFingerprint } +// Where each pairing's next page starts, per database, when more conversations are pending than a page holds. +const pullRotations = new WeakMap>() + +/** Every conversation with pending items gets an equal share of the page, so an item the paired Orca + * cannot import yet, which stays at its conversation's head, never starves another conversation. */ function pendingReplies(db: OrchestrationDb, peerFingerprint: string): FederationRelayItemRow[] { - const items: FederationRelayItemRow[] = [] - for (const conversationId of db.listPeerConversationIds(peerFingerprint)) { - if (items.length >= PULL_PAGE_SIZE) { - break - } - items.push( - ...db.listPendingFederationRelay(conversationId, 'to_home', PULL_PAGE_SIZE - items.length) - ) - } - return items + const pending = db + .listPeerConversationIds(peerFingerprint) + .filter((id) => db.listPendingFederationRelay(id, 'to_home', 1).length > 0) + const share = Math.max(1, Math.floor(PULL_PAGE_SIZE / pending.length)) + const pullRotation = pullRotations.get(db.db) ?? new Map() + pullRotations.set(db.db, pullRotation) + const start = pending.length > PULL_PAGE_SIZE ? (pullRotation.get(peerFingerprint) ?? 0) : 0 + pullRotation.set(peerFingerprint, (start + PULL_PAGE_SIZE) % Math.max(1, pending.length)) + return [...pending.slice(start), ...pending.slice(0, start)] + .slice(0, PULL_PAGE_SIZE) + .flatMap((id) => db.listPendingFederationRelay(id, 'to_home', share)) + .slice(0, PULL_PAGE_SIZE) } export const ORCHESTRATION_PEER_MAIL_METHODS = [ @@ -154,8 +161,10 @@ export const ORCHESTRATION_PEER_MAIL_METHODS = [ const db = ctx.runtime.getOrchestrationDb() let items = pendingReplies(db, peerFingerprint) const waitMs = Math.min(Math.max(params.waitMs ?? 0, 0), MAX_PULL_WAIT_MS) - if (items.length === 0 && waitMs > 0) { - await waitForPeerMail(db, waitMs, ctx.signal) + const deadline = Date.now() + waitMs + // A wake is any queued change on this Orca, so one that queued nothing for this peer waits on. + while (items.length === 0 && Date.now() < deadline && !ctx.signal?.aborted) { + await waitForPeerMail(db.db, deadline - Date.now(), ctx.signal) items = pendingReplies(ctx.runtime.getOrchestrationDb(), peerFingerprint) } return { @@ -163,6 +172,7 @@ export const ORCHESTRATION_PEER_MAIL_METHODS = [ conversationId: item.dispatch_id, sequence: item.sequence, messageId: item.message_id, + kind: item.kind, payload: item.payload })) } diff --git a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail.test.ts index c624b2989fa..54dc45a324f 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail.test.ts @@ -293,19 +293,6 @@ describe('agent mail between paired Orca servers', () => { expect(b.db.getInbox(10).filter((message) => message.subject === 'Once')).toHaveLength(1) }) - it('refuses payload fields before sending anything', async () => { - const sent = await mutation(a, 'orchestration.send', { - from: 'term_a', - on: 'devB', - to: 'term_b', - subject: 'Report', - payload: '{"taskId":"task_1"}' - }) - - expect(sent).toMatchObject({ ok: false, error: { code: 'invalid_argument' } }) - expect(b.db.getInbox(10)).toEqual([]) - }) - it('refuses mail to a worker another Orca coordinates', async () => { vi.spyOn(b.db, 'findActiveRemoteAttachmentForPane').mockImplementation((paneKey) => // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a test double carrying only the fields the code under test reads. @@ -323,19 +310,6 @@ describe('agent mail between paired Orca servers', () => { expect(b.db.getInbox(10)).toEqual([]) }) - it('refuses a conversation ID that is not a peer conversation', async () => { - const delivered = await transport.call('devB', 'orchestration.peerMailDeliver', { - conversationId: 'ctx_aaaaaaaaaaaa', - messageId: 'msg_aaaaaaaaaaaa', - to: 'term_b', - senderLabel: "term_a on Jinwoo's Mac", - subject: 'Into a dispatch' - }) - - expect(delivered).toMatchObject({ ok: false, error: { code: 'invalid_argument' } }) - expect(b.db.getInbox(10)).toEqual([]) - }) - it('keeps conversing with a server after it is re-paired', async () => { await mutation(a, 'orchestration.send', { from: 'term_a', @@ -385,7 +359,7 @@ describe('agent mail between paired Orca servers', () => { a.db.resetMessages() // The ack was lost: the server serves the stored reply again. b.db['db'].prepare('UPDATE federation_relay_items SET acked_at = NULL').run() - notifyPeerMailQueued(b.db) + notifyPeerMailQueued(b.db.db) await vi.waitFor(() => expect(b.db.listPendingFederationRelay(conversationId!, 'to_home')).toEqual([]) diff --git a/src/main/runtime/rpc/methods/orchestration/federation/peer-run-methods.ts b/src/main/runtime/rpc/methods/orchestration/federation/peer-run-methods.ts new file mode 100644 index 00000000000..a64ce31c976 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/federation/peer-run-methods.ts @@ -0,0 +1,54 @@ +import { defineOrchestrationMethod } from '../access/orchestration-method-access' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import { WORKER_SETTLED_STATES } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' +import { + PeerRunCancelParams, + type PeerRunCancelResult +} from '../../../../../../shared/orchestration/remote-owned-wire' +import type { z } from 'zod' +import { stopWorkerAndHelpers } from '../worker/worker-stop' + +export const ORCHESTRATION_PEER_RUN_METHODS = [ + defineOrchestrationMethod({ + name: 'orchestration.peerRunCancel', + access: { kind: 'writes', targets: {} }, + permission: 'workspace', + params: PeerRunCancelParams, + /** The paired Orca reset its Run: close it here, then run the ordinary stop on each live worker. */ + handler: async (_params, { runtime, orchestrationCaller }) => { + if (orchestrationCaller?.kind !== 'peer') { + throw new OrchestrationError( + 'forbidden', + 'Only the paired Orca that coordinates a Run cancels it. No effects were applied.', + { effectsApplied: false } + ) + } + const db = runtime.getOrchestrationDb() + const runId = orchestrationCaller.peerRun.run_id + // Committed before any stop, so nothing more starts in it while the stops run. + db.closePeerRun(runId) + for (const dispatchId of liveWorkerDispatchIds(db, runId)) { + // Each stop's own outcome stays on its Dispatch; the count below is the answer. + await stopWorkerAndHelpers(runtime, dispatchId, undefined).catch(() => undefined) + } + const result: z.infer = { + remaining: liveWorkerDispatchIds(db, runId).length + } + return result + } + }) +] + +/** Workers in the Run not yet proven settled; a Run this Orca never had work in has none. */ +function liveWorkerDispatchIds(db: OrchestrationDb, runId: string): string[] { + const settled = WORKER_SETTLED_STATES.map(() => '?').join(', ') + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT of one column returns exactly that column. + const rows = db.db + .prepare( + `SELECT d.id FROM dispatch_contexts d JOIN worker_dispatches w ON w.dispatch_id = d.id + WHERE d.run_id = ? AND w.state NOT IN (${settled}) ORDER BY d.rowid` + ) + .all(runId, ...WORKER_SETTLED_STATES) as { id: string }[] + return rows.map((row) => row.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 cc9251aeff5..11af8dd3c25 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts @@ -22,6 +22,7 @@ export const ORCHESTRATION_CHECK_METHODS = [ access: { kind: 'writes', caller: 'terminal', + callerPane: 'terminalPaneKey', targets: { run: 'run', ack: 'message' }, collection: true }, 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 2b90558c392..31ec54fb285 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 @@ -7,7 +7,7 @@ import { acknowledgedOnlyReceipt, handsOverBatch } from './mailbox-message-recei import { currentDispatchAssigneeRun } from './recipient-routing' import { callerHoldsDispatchPane, dispatchFenced } from './dispatch-mailbox-fence' import { orchestrationCallerIdentity } from '../runs/run-scope' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import type { CheckParams } from '../../../../../../shared/rpc-contract/orchestration-params' import type { z } from 'zod' @@ -18,7 +18,7 @@ export async function checkRunPendingMail(args: { run: RunRow handle: string paneKey: string | undefined - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined typeFilter: MessageType[] | undefined signal: AbortSignal | undefined revalidateConsumer: () => void 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 49ef6a58dbe..b52ac709c7e 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/check-run.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/check-run.ts @@ -11,7 +11,7 @@ import { routeAllMailboxPages } from './mailbox-page-routing' import { resolveRunScope } from '../runs/run-scope' import type { CheckParams } from '../../../../../../shared/rpc-contract/orchestration-params' import type { z } from 'zod' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import { checkRunPendingMail } from './check-run-pending-mail' import { FEDERATION_RELAY_WAIT_REARM_MS } from '../../../../orchestration/federation/relay/federation-relay-scheduler' @@ -23,7 +23,7 @@ export async function checkRunMailbox(args: { db: OrchestrationDb handle: string paneKey: string | undefined - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined typeFilter: MessageType[] | undefined signal: AbortSignal | undefined legacyCoordinatorRunId: string | undefined diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/helper-question-answerer.ts b/src/main/runtime/rpc/methods/orchestration/messaging/helper-question-answerer.ts index d38486eb25d..944a3dfcb14 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/helper-question-answerer.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/helper-question-answerer.ts @@ -1,5 +1,5 @@ import type { OrchestrationCompatibilityEvidence } from '../../../../../../shared/orchestration/orchestration-compatibility-evidence' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import type { MessageRow } from '../../../../orchestration/db/orchestration-records' import type { OrcaRuntimeService } from '../../../../orca-runtime' import { assertCallerHandleMatchesEvidence, orchestrationCallerIdentity } from '../runs/run-scope' @@ -10,7 +10,7 @@ export function helperQuestionAnswerer( args: { question: MessageRow from: string | undefined - session: OrchestrationSessionCaller | undefined + session: OrchestrationEntryCaller | undefined evidence: OrchestrationCompatibilityEvidence | undefined } ): { dispatchId: string; consumerGeneration: number } | undefined { 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 027c7f424e3..fff196ea676 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts @@ -18,16 +18,18 @@ export const ORCHESTRATION_MESSAGE_METHODS = [ name: 'orchestration.inbox', permission: 'workspace', params: InboxParams, - access: { kind: 'reads', targets: { terminal: 'party' }, collection: true }, + access: { kind: 'reads', targets: { terminal: 'party', run: 'run' }, collection: true }, handler: (params, { runtime }) => { const db = runtime.getOrchestrationDb() // Return empty for stale/unknown handles because historical mail outlives handle deletion (design doc §3.3). const messages = params.terminal ? db.getAllMessagesForHandle( resolveOrchestrationParty(params.terminal, db).address, - params.limit + params.limit, + undefined, + params.run ) - : db.getInbox(params.limit) + : db.getInbox(params.limit, params.run) return { messages: messages.map(({ answer_sender_snapshot: _answer, ...message }) => message), count: messages.length diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-reply.ts b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-reply.ts index e78a9abda6a..f23c85fdc82 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-reply.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-reply.ts @@ -1,5 +1,5 @@ import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import type { PeerMailMessageRow } from '../../../../orchestration/db/federation/peer-mail-store' import type { MessageRow } from '../../../../orchestration/db/orchestration-records' import { OrchestrationError } from '../../../../orchestration/orchestration-error' @@ -21,7 +21,7 @@ export async function replyOverPeerMail(args: { original: MessageRow route: PeerMailMessageRow params: { body: string; from?: string; on?: string } - orchestrationCaller: OrchestrationSessionCaller | undefined + orchestrationCaller: OrchestrationEntryCaller | undefined orchestrationMutation: { callerFingerprint: string; requestId: string } | undefined recordMutationReceipt: ((receipt: unknown) => void) | undefined }): Promise { @@ -67,7 +67,7 @@ export async function replyOverPeerMail(args: { return recordReceiptBeforeNudge( args.recordMutationReceipt, { message: { id, subject }, to: original.from_handle }, - () => notifyPeerMailQueued(db), + () => notifyPeerMailQueued(db.db), { kind: 'messages', targets: [] } ) } diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts index a9fa69344b3..a18969d81c4 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts @@ -1,6 +1,6 @@ import type { z } from 'zod' import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import type { OrchestrationCompatibilityCallerAuthority } from '../../../../orchestration/terminal-authority/orchestration-compatibility-authority' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { @@ -20,7 +20,7 @@ const NOTHING_SENT = { effectsApplied: false } as const export function peerMailLocalCaller(args: { runtime: OrcaRuntimeService from: string | undefined - orchestrationCaller: OrchestrationSessionCaller | undefined + orchestrationCaller: OrchestrationEntryCaller | undefined attestedCaller: OrchestrationCompatibilityCallerAuthority | undefined }): { address: string; paneKey: string | null } { if (args.orchestrationCaller) { @@ -51,7 +51,7 @@ export function peerMailLocalCaller(args: { export async function sendPeerMail(args: { params: z.infer & { on: string } runtime: OrcaRuntimeService - orchestrationCaller: OrchestrationSessionCaller | undefined + orchestrationCaller: OrchestrationEntryCaller | undefined attestedCaller: OrchestrationCompatibilityCallerAuthority | undefined orchestrationMutation: { callerFingerprint: string; requestId: string } | undefined recordMutationReceipt: ((receipt: unknown) => void) | undefined 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 94e0996ac2d..19d52a02e68 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts @@ -29,6 +29,7 @@ export const ORCHESTRATION_REPLY_METHOD = defineOrchestrationMethod({ access: { kind: 'writes', caller: 'from', + server: 'on', targets: { id: 'message', run: 'run' }, rule: replyAccess }, 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 1d9c485e919..a0ad726c0cd 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts @@ -39,6 +39,8 @@ export const ORCHESTRATION_SEND_METHODS = [ access: { kind: 'writes', caller: 'from', + callerPane: 'senderPaneKey', + server: 'on', targets: { to: 'party', threadId: 'message', run: 'run', payload: 'dispatch' } }, permission: 'workspace', @@ -172,6 +174,17 @@ export const ORCHESTRATION_SEND_METHODS = [ if (!recipient.ok) { throw new OrchestrationError(recipient.code, recipient.message) } + // A paired Orca's former worker may since have taken up local work; it is no longer its to reach. + if ( + orchestrationCaller?.kind === 'peer' && + recipient.runId !== orchestrationCaller.peerRun.run_id + ) { + throw new OrchestrationError( + 'forbidden', + `${params.to} now works outside the Run ${orchestrationCaller.peerRun.home_label} coordinates here. No effects were applied.`, + { effectsApplied: false } + ) + } to = recipient.to messageRunId = recipient.runId if (recipient.warning) { 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 56273cfec5a..85752b5aa3d 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 @@ -8,6 +8,7 @@ import { reconcileLifecycleMessage } from '../../../../orchestration/workers/lif import { bindCoordinatorMutationPayload } from '../../../../orchestration/workers/reports/dispatch-message-binding' import { isDispatchMutationMessageType } from '../../../../../../shared/rpc-contract/orchestration-params' import { parseMessageTaskId } from './message-payload' +import { isDispatchAssignee } from '../../../../orchestration/db/dispatch-context/dispatch-lookup' import type { SendParams } from './send-params' import { legacyWorkerDeliveryContract } from '../routing' import { exposeMessage } from './mailbox-message-receipt' @@ -74,6 +75,8 @@ export function sendPointToPointMessage(args: { ? bindCoordinatorMutationPayload(messageType, params.payload, dispatch.id) : params.payload, senderPaneKey, + senderDispatchId: + dispatch && isDispatchAssignee(dispatch, from, senderPaneKey) ? dispatch.id : undefined, runId: messageRunId, deliveryContract: legacyWorkerDeliveryContract( runtime, 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 fc223637a6a..3aec8ace463 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 @@ -10,7 +10,11 @@ import { receivesMailWhole } from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' import { FOLLOW_UP_MESSAGE_TYPES } from '../../../../orchestration/db/dispatch-context/worker-follow-up-plan' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import { + peerCoordinatorAddress, + peerCoordinatorCaller, + type OrchestrationEntryCaller +} from '../../../../orchestration/addressing/orchestration-caller-identity' import { resolveOrcaSessionParty } from '../../../../orchestration/addressing/orchestration-party' import { readStructuredAgentSessionRecord } from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' import { createHash } from 'node:crypto' @@ -111,7 +115,7 @@ async function continueUnreadMail( outcome = plan?.kind === 'start' ? await startWorkerFollowUp({ - ctx: { runtime, orchestrationCaller: senderSession(db, first.from_handle) }, + ctx: { runtime, orchestrationCaller: senderCaller(db, first) }, db, plan, from: first.from_handle, @@ -304,7 +308,16 @@ export function continueAllUnreadWorkerMail( } } -function senderSession(db: OrchestrationDb, from: string): OrchestrationSessionCaller | undefined { +/** The sender continues as itself: a session as its session, a paired Orca as the coordinator of its Run. */ +function senderCaller( + db: OrchestrationDb, + message: { from_handle: string; run_id: string } +): OrchestrationEntryCaller | undefined { + const peerRun = db.getPeerRun(message.run_id) + if (peerRun && message.from_handle === peerCoordinatorAddress(peerRun.conversation_id)) { + return peerCoordinatorCaller(peerRun) + } + const from = message.from_handle const sessionId = parseOrcaSessionAddress(from) const record = sessionId ? readStructuredAgentSessionRecord(sessionId) : null return sessionId && record diff --git a/src/main/runtime/rpc/methods/orchestration/orchestration-caller-workspace.ts b/src/main/runtime/rpc/methods/orchestration/orchestration-caller-workspace.ts index d22964215f7..ce78dca6226 100644 --- a/src/main/runtime/rpc/methods/orchestration/orchestration-caller-workspace.ts +++ b/src/main/runtime/rpc/methods/orchestration/orchestration-caller-workspace.ts @@ -2,14 +2,18 @@ * showTerminal requires a real PTY; fabricating its writable fields would break terminal verbs for chat workers. */ import type { OrcaRuntimeService } from '../../../orca-runtime' -import type { OrchestrationSessionCaller } from '../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../../orchestration/addressing/orchestration-caller-identity' import { isStructuredWorkerHandle } from '../../../../../shared/orchestration/workers/structured-worker-handle' export async function resolveDispatchCallerWorktreeId( runtime: Pick, callerHandle: string, - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined ): Promise { + // A paired Orca has no workspace here, so `current` and `new-child` refuse as for an unmanaged one. + if (callerSession?.kind === 'peer') { + return PEER_COORDINATOR_HAS_NO_WORKSPACE + } // A session caller's workspace is on its record, whichever owner (chat or terminal) holds it. if (callerSession) { return callerSession.workspaceId @@ -22,3 +26,5 @@ export async function resolveDispatchCallerWorktreeId( } return (await runtime.showTerminal(callerHandle)).worktreeId } + +const PEER_COORDINATOR_HAS_NO_WORKSPACE = 'peer-coordinator-has-no-workspace' diff --git a/src/main/runtime/rpc/methods/orchestration/runs/dispatch-creator.ts b/src/main/runtime/rpc/methods/orchestration/runs/dispatch-creator.ts index c43da58338e..fb415f5b858 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/dispatch-creator.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/dispatch-creator.ts @@ -1,5 +1,5 @@ import type { DispatchCreator } from '../../../../orchestration/db/dispatch-depth' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import type { OrcaRuntimeService } from '../../../../orca-runtime' import { orchestrationCallerIdentity } from './run-scope' @@ -7,7 +7,7 @@ import { orchestrationCallerIdentity } from './run-scope' export function resolveDispatchCreator( runtime: OrcaRuntimeService, callerHandle: string | undefined, - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined ): DispatchCreator { if (!callerHandle) { // No declared caller resolves no parent; retain legacy Run-binding depth zero. diff --git a/src/main/runtime/rpc/methods/orchestration/runs/run-scope.ts b/src/main/runtime/rpc/methods/orchestration/runs/run-scope.ts index a5993600973..5d59eb85261 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/run-scope.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/run-scope.ts @@ -8,7 +8,7 @@ import { hasRunBindingKey, mailboxAddressOf, runCoordinatorKey, - type OrchestrationSessionCaller + type OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import type { OrchestrationPartyIdentity as OrchestrationCallerIdentity } from '../../../../../../shared/orchestration/mailbox/orchestration-party-identity' import { resolveDeclaredCallerParty } from '../../../../orchestration/addressing/orchestration-party' @@ -24,7 +24,7 @@ export type RunScopeParams = { callerTerminalHandle?: string callerPaneKey?: string /** Resolved at the dispatch entry; when set it is the caller, whatever the declared handle. */ - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined requireCurrentConsumer: boolean legacyCoordinatorRunId?: string // Attest user-supplied handles against this trusted handle. @@ -56,7 +56,7 @@ export function orchestrationCallerIdentity( caller: { handle: string paneKey: string | null | undefined - session: OrchestrationSessionCaller | undefined + session: OrchestrationEntryCaller | undefined } ): OrchestrationCallerIdentity { if (caller.session) { @@ -70,7 +70,7 @@ export type OrchestrationCallerParams = { callerTerminalHandle: string callerEvidence?: OrchestrationCompatibilityEvidence callerAuthority?: OrchestrationCompatibilityCallerAuthority - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined /** Preserve legacy callers that treated a missing pane as an ordinary fence. */ requireStablePane?: boolean /** Only skip attestation when the caller does it after the legacy-takeover check (run-use); omitting that reopens impersonation. */ diff --git a/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts b/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts index da0075d287c..dc79fd4eef1 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts @@ -60,6 +60,7 @@ export async function deliverWorkerDispatchPreamble(args: { dispatchId: args.dispatchId, taskSpec: args.taskSpec, coordinatorHandle: orcaSessionIdOrHandle(args.coordinatorHandle, args.db), + coordinatedFrom: args.db.getPeerRun(args.runId)?.home_label, // Its mailbox stays keyed by the handle; its commands name its Orca session ID, which binds to it. workerHandle: structuredSession && isOrcaSessionId(structuredSession.identity.sessionId) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/explicit-worker-terminal-validation.ts b/src/main/runtime/rpc/methods/orchestration/worker/explicit-worker-terminal-validation.ts index a2d53e01de2..6adb724d6f9 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/explicit-worker-terminal-validation.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/explicit-worker-terminal-validation.ts @@ -1,5 +1,6 @@ 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, @@ -27,8 +28,9 @@ export async function assertExplicitWorkerTerminalUsable(args: { const targetPane = runtime.getTerminalPaneKey(terminal) const callerPane = coordinator?.paneKey ?? runtime.getTerminalPaneKey(from) // Structured coordinators may have no showable terminal; compare their handle/pane identity, or session address for handle-less callers. + // A paired Orca's coordinator has no terminal here either; its address is its handle. const coordinatorHandle = - coordinator?.terminalHandle === null + coordinator?.terminalHandle === null || isPeerCaller(coordinator) ? coordinator.address : isStructuredWorkerHandle(from) ? from diff --git a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts index 5d26db76cb2..50ee585d311 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts @@ -64,6 +64,7 @@ export function createLocalWorkerStartDispatch( requiredCreatorDispatchId: helperCreator?.id, taskId: existingTask?.id, taskSpec: params.spec, + adoptTaskId: params.adoptTaskId, taskTitle: params.taskTitle, taskDeps, // A helper's Task sits under its creator's Task, so the Run's Task tree shows who started it. diff --git a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts index 1af01cf6710..6d7446b10f6 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts @@ -11,7 +11,7 @@ import type { RunRow, TaskRow } from '../../../../orchestration/db/orchestration-records' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +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' @@ -48,7 +48,7 @@ export async function startLocalWorker(args: { bindRun: () => RunRow taskDeps: string[] | undefined coordinator: OrchestrationCallerIdentity | null - callerSession?: OrchestrationSessionCaller + callerSession?: OrchestrationEntryCaller existingTask?: TaskRow orchestrationMutation?: WorkerStartMutation /** Settings-driven; the executing host still gets to refuse below. */ 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 b506a17124f..c8083a27648 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 @@ -251,6 +251,7 @@ async function projectWorkerListPageWithFilteredSnapshot( dispatchStatus: row.dispatchStatus, agentTerminalHandle: row.agentTerminalHandle, terminalState: row.terminalState, + coordinatedFrom: row.coordinatedFrom, resource: row.resource ? exposeWorkerTerminalResource(row.resource) : null, // Emit only derived ownership; resource identity/release fields already live on the row. projection: { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-authority.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-authority.ts index 3df8bd1e22f..d54f92f4c16 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-authority.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-authority.ts @@ -4,7 +4,7 @@ import { liveDispatchCreatorEvaluation } from '../../../../orchestration/db/disp import { selectExistingWorkerStartRun } from './worker-start-run-authority' import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import type { OrchestrationPartyIdentity as OrchestrationCallerIdentity } from '../../../../../../shared/orchestration/mailbox/orchestration-party-identity' import type { DispatchContextRow, @@ -27,7 +27,7 @@ export function resolveWorkerStartRun( args: { coordinator: OrchestrationCallerIdentity | null from: string - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined runId: string | undefined /** Objective for a Run this start may create; absent when it names an existing Task. */ objective: string | undefined @@ -120,7 +120,7 @@ export function qualifyLiveWorkerFollowUp( runtime: OrcaRuntimeService, coordinator: OrchestrationCallerIdentity | null, from: string, - session: OrchestrationSessionCaller | undefined, + session: OrchestrationEntryCaller | undefined, runId: string, followUp: Parameters>[1] ) { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts b/src/main/runtime/rpc/methods/orchestration/worker/workers.ts index dcf2e63ef94..2538b27521b 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/workers.ts @@ -40,13 +40,15 @@ export const ORCHESTRATION_WORKER_START_METHODS = [ access: { kind: 'writes', caller: 'from', + server: 'on', targets: { task: 'task', parent: 'task', deps: 'task', run: 'run', retryOf: 'dispatch', - terminal: 'worker' + terminal: 'worker', + adoptTaskId: 'task' } }, requires: ['accounts'], @@ -81,6 +83,26 @@ export async function startWorker( { 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 readinessTimeoutMs = resolveWorkerStartReadinessTimeoutMs(params.timeoutMs) const db = runtime.getOrchestrationDb() const coordinator = resolveOrchestrationCaller(runtime, { diff --git a/src/main/runtime/rpc/orchestration-mutation-executor.test.ts b/src/main/runtime/rpc/orchestration-mutation-executor.test.ts index 2bda0a49813..c3e7a5466b8 100644 --- a/src/main/runtime/rpc/orchestration-mutation-executor.test.ts +++ b/src/main/runtime/rpc/orchestration-mutation-executor.test.ts @@ -50,6 +50,7 @@ function createHarness() { 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 }) @@ -236,3 +237,27 @@ describe('worker start mutation coalescing', () => { 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-executor.ts b/src/main/runtime/rpc/orchestration-mutation-executor.ts index 2569a8d0e6e..a20faeb6649 100644 --- a/src/main/runtime/rpc/orchestration-mutation-executor.ts +++ b/src/main/runtime/rpc/orchestration-mutation-executor.ts @@ -3,7 +3,7 @@ import { isTerminalPromptMutation } from '../../../shared/orchestration/orchestration-rpc-contract' import type { OrcaRuntimeService } from '../orca-runtime' -import type { OrcaSessionId } from '../../../shared/orca-session-address' +import type { OrchestrationEntryCaller } from '../orchestration/addressing/orchestration-caller-identity' import { OrchestrationError } from '../orchestration/orchestration-error' import type { RpcRequest } from './core' import { @@ -32,6 +32,14 @@ export type DurableMutationInvocation = { replayedReceipt?: unknown } +/** Mutations whose pending receipt a restart re-enters, so a stop or cancel still finishes rather + * than answering operation_unknown: each re-runs its ordinary owner, which is safe to repeat. */ +const RESUMABLE_PENDING_METHODS: ReadonlySet = new Set([ + 'orchestration.workerRelease', + 'orchestration.workerStop', + 'orchestration.peerRunCancel' +]) + type InFlightMutation = { method: string payloadHash: string @@ -48,8 +56,8 @@ export class OrchestrationMutationExecutor { params: unknown, invoke: (mutation?: DurableMutationInvocation) => unknown, callerFingerprintOverride?: string, - /** The resolved session's Orca session id; it joins the payload so another caller cannot replay it. */ - callerOrcaSessionId?: OrcaSessionId + /** The resolved caller; its identity joins the payload so another caller cannot replay it. */ + caller?: OrchestrationEntryCaller ): Promise { const requestId = request.orchestrationRequestId if (!requestId || !isDurableMutation(request.method, params)) { @@ -57,12 +65,7 @@ export class OrchestrationMutationExecutor { } const callerFingerprint = callerFingerprintOverride ?? this.getLocalAuthenticatedCallerFingerprint() - const stableParams = replayStableCallerParams( - this.runtime, - params, - callerOrcaSessionId, - request.method - ) + const stableParams = replayStableCallerParams(this.runtime, params, caller, request.method) const basePayloadHash = hashCanonical({ method: request.method, params: stableParams }) const key = `${callerFingerprint}:${requestId}` const db = this.runtime.getOrchestrationDb() @@ -134,7 +137,7 @@ export class OrchestrationMutationExecutor { isResumablePendingWorkerDone(request.method, params, begun.row.receipt) const resumedPendingMutation = begun.disposition === 'pending' && - (request.method === 'orchestration.workerRelease' || resumedPendingWorkerDone) + (RESUMABLE_PENDING_METHODS.has(request.method) || resumedPendingWorkerDone) if (begun.disposition === 'completed') { const active = this.inFlight.get(key) @@ -191,7 +194,7 @@ export class OrchestrationMutationExecutor { { requestId } ) } - if (request.method !== 'orchestration.workerRelease' && !resumedPendingWorkerDone) { + if (!resumedPendingMutation) { const recovery = getPendingWorkerStartRecovery(request.method, begun.row.receipt) throw new OrchestrationError( 'operation_unknown', diff --git a/src/main/runtime/rpc/orchestration-mutation-receipt.ts b/src/main/runtime/rpc/orchestration-mutation-receipt.ts index 03cf9ebd9d7..ed20925ed9a 100644 --- a/src/main/runtime/rpc/orchestration-mutation-receipt.ts +++ b/src/main/runtime/rpc/orchestration-mutation-receipt.ts @@ -2,7 +2,7 @@ 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 { OrcaSessionId } from '../../../shared/orca-session-address' +import type { OrchestrationEntryCaller } from '../orchestration/addressing/orchestration-caller-identity' export const EFFECT_FREE_WORKER_DONE_CHECKPOINT = JSON.stringify({ pending: { effectFree: 'worker_done' } @@ -15,11 +15,13 @@ export type MutationReplayNudge = | { kind: 'federation'; runId?: string } const CALLER_ORCA_SESSION_ID_KEY = '__orcaCallerOrcaSessionId' +// A paired Orca's address names its conversation, so one Run's receipt never answers another's. +const PEER_CALLER_KEY = '__orcaPeerCaller' export function replayStableCallerParams( runtime: OrcaRuntimeService, params: unknown, - callerOrcaSessionId?: OrcaSessionId, + caller?: OrchestrationEntryCaller, method?: string ): unknown { if (!params || typeof params !== 'object' || Array.isArray(params)) { @@ -27,9 +29,12 @@ export function replayStableCallerParams( } const source = params as Record // Absent for terminal callers, so their payload hashes are unchanged. - const result: Record = callerOrcaSessionId - ? { ...source, [CALLER_ORCA_SESSION_ID_KEY]: callerOrcaSessionId } - : { ...source } + const result: Record = + caller?.kind === 'peer' + ? { ...source, [PEER_CALLER_KEY]: caller.address } + : caller?.orcaSessionId + ? { ...source, [CALLER_ORCA_SESSION_ID_KEY]: caller.orcaSessionId } + : { ...source } if (method === 'orchestration.federationImport' && Array.isArray(result.items)) { result.items = result.items.map((item: Record) => { const { answerSenderReport: _answer, ...canonical } = item diff --git a/src/main/runtime/rpc/orchestration-peer-caller.ts b/src/main/runtime/rpc/orchestration-peer-caller.ts new file mode 100644 index 00000000000..f57053b9d88 --- /dev/null +++ b/src/main/runtime/rpc/orchestration-peer-caller.ts @@ -0,0 +1,72 @@ +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 { + peerCoordinatorCaller, + type OrchestrationPeerCaller +} from '../orchestration/addressing/orchestration-caller-identity' + +const NO_EFFECTS = { effectsApplied: false } as const + +/** + * A call a paired Orca makes as the coordinator of one of its Runs here. Admitted from the + * authenticated runtime pairing, never from a param, and synchronously: its Run is written in the + * frame's first turn, so a later frame of the same conversation (a cancel) always finds it. + * The declared caller field then names the peer, as a session's names the session. + */ +export function admitOrchestrationPeerCall( + runtime: OrcaRuntimeService, + request: RpcRequest, + method: RpcMethod | RpcStreamingMethod, + options: RpcDispatchStreamingOptions | undefined +): { request: RpcRequest; caller: OrchestrationPeerCaller } | undefined { + if (request.orchestrationPeerRun === undefined) { + return undefined + } + const access = method.orchestrationAccess + if (!access) { + throw new OrchestrationError( + 'invalid_argument', + `${request.method} is not an orchestration method, so it takes no peer Run. No effects were applied.`, + NO_EFFECTS + ) + } + const fingerprint = options?.authenticatedCallerFingerprint + if (options?.clientKind !== 'runtime' || options.pairedDeviceId === undefined || !fingerprint) { + throw new OrchestrationError( + 'mail_requires_server_pairing', + 'Only a paired computer can coordinate a Run on this server. No effects were applied.', + NO_EFFECTS + ) + } + const peerRun = RemoteOwnedPeerRun.safeParse(request.orchestrationPeerRun) + if (!peerRun.success || !isGeneratedId(peerRun.data.conversationId, 'peerconv')) { + throw new OrchestrationError( + 'invalid_argument', + 'A peer Run needs its Run, conversation ID and label. No effects were applied.', + NO_EFFECTS + ) + } + const caller = peerCoordinatorCaller( + runtime + .getOrchestrationDb() + .admitPeerRun({ peerFingerprint: fingerprint, peerRun: peerRun.data }) + ) + // Terminal attestation and pane keys name callers on the host that has them, never this one. + const peerRequest = { ...request, orchestrationCompatibilityEvidence: undefined } + const params: unknown = request.params + if (!params || typeof params !== 'object' || Array.isArray(params)) { + return { request: peerRequest, caller } + } + const bound: Record = { ...params } + if (access.callerPane) { + delete bound[access.callerPane] + } + if (access.caller) { + bound[access.caller] = caller.address + } + return { request: { ...peerRequest, params: bound }, caller } +} diff --git a/src/main/runtime/rpc/orchestration-session-caller.ts b/src/main/runtime/rpc/orchestration-session-caller.ts index 10a82436696..160cf758f1e 100644 --- a/src/main/runtime/rpc/orchestration-session-caller.ts +++ b/src/main/runtime/rpc/orchestration-session-caller.ts @@ -11,7 +11,10 @@ import { ORCA_SESSION_ADDRESS_PREFIX } from '../../../shared/orca-session-addres 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 { OrchestrationSessionCaller } from '../orchestration/addressing/orchestration-caller-identity' +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' @@ -36,7 +39,7 @@ export type OrchestrationRequestRoute = { export type ResolvedOrchestrationRequest = { /** The request with its declared caller bound to the session and its evidence reduced to it. */ request: RpcRequest - caller?: OrchestrationSessionCaller + caller?: OrchestrationEntryCaller } const NO_EFFECTS = { effectsApplied: false } as const diff --git a/src/main/runtime/rpc/repo-add-cli.integration.test.ts b/src/main/runtime/rpc/repo-add-cli.integration.test.ts index e5e71c09e88..4e0332a61df 100644 --- a/src/main/runtime/rpc/repo-add-cli.integration.test.ts +++ b/src/main/runtime/rpc/repo-add-cli.integration.test.ts @@ -13,14 +13,17 @@ import { partialRuntimeStore } from '../orca-runtime-tests/runtime-store-partial 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('../../repository-icons/repo-icon-autodetect', () => ({ - detectRepoIconAndUpstream: vi.fn().mockResolvedValue({}) -})) vi.mock('../../workspaces/creation/worktree-root-preparation', () => ({ prepareLocalWorktreeRootForRepo: vi.fn().mockResolvedValue(undefined) })) +vi.mock('../../git/command-runner/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({ @@ -43,9 +46,19 @@ it('opens a repo-tool root through the CLI folder route and keeps subproject Git invalidateWorktreeScan: () => {}, notifyReposChanged: () => {} }) + const metadata = new RuntimeRepositoryForkBackfill( + () => store, + () => {} + ) + let background = Promise.resolve() + let heldSlots = 0 const dispatcher = repoDispatcher({ getRuntimeId: () => 'repo-cli-test', - addRepo: (...args) => controller.add(...args), + addRepo: async (...args) => { + const repo = await controller.add(...args) + background = metadata.enqueue([repo]) + return repo + }, listVisibleRepos: () => repos, requireStore: () => store }) @@ -79,6 +92,11 @@ it('opens a repo-tool root through the CLI folder route and keeps subproject Git 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), @@ -114,6 +132,10 @@ it('opens a repo-tool root through the CLI folder route and keeps subproject Git 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 @@ -122,6 +144,19 @@ it('opens a repo-tool root through the CLI folder route and keeps subproject Git 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 @@ -132,6 +167,11 @@ it('opens a repo-tool root through the CLI folder route and keeps subproject Git expect(requests).toHaveLength(beforeInvalid) expect(repos).toHaveLength(2) } finally { + while (heldSlots > 0) { + release() + heldSlots-- + } + await background await socket.stop() vi.unstubAllEnvs() process.exitCode = previousExitCode diff --git a/src/main/runtime/rpc/rpc-active-caller.ts b/src/main/runtime/rpc/rpc-active-caller.ts index 51b324d3993..975ec4fbdcc 100644 --- a/src/main/runtime/rpc/rpc-active-caller.ts +++ b/src/main/runtime/rpc/rpc-active-caller.ts @@ -1,14 +1,40 @@ import { AsyncLocalStorage } from 'node:async_hooks' -import type { RpcCallerIdentity } from './rpc-caller-identity' +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 activeCaller = new AsyncLocalStorage() +const activeCall = new AsyncLocalStorage() -export function runWithActiveRpcCaller(caller: RpcCallerIdentity | undefined, run: () => T): T { - return activeCaller.run(caller, run) +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 activeCaller.getStore() + 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/rpc-request-admission-prologue.ts b/src/main/runtime/rpc/rpc-request-admission-prologue.ts index ee6560cea66..fa0deb52116 100644 --- a/src/main/runtime/rpc/rpc-request-admission-prologue.ts +++ b/src/main/runtime/rpc/rpc-request-admission-prologue.ts @@ -23,6 +23,7 @@ import { resolveOrchestrationSessionCaller, type ResolvedOrchestrationRequest } from './orchestration-session-caller' +import { admitOrchestrationPeerCall } from './orchestration-peer-caller' type RpcRequestAdmissionDeps = { runtime: OrcaRuntimeService @@ -59,6 +60,13 @@ export function admitRpcRequest( return reject(migrationFence) } + let peer: ReturnType + try { + peer = admitOrchestrationPeerCall(runtime, rawRequest, method, options) + } catch (error) { + return reject(mapDispatcherError(rawRequest, meta, error)) + } + const admitResolved = ({ request, caller }: ResolvedOrchestrationRequest) => { const parsedParams = parseRpcRequestParams(request, method, meta) if (parsedParams.error) { @@ -76,6 +84,9 @@ export function admitRpcRequest( } return { method, request, caller, params: parsedParams.value } } + if (peer) { + return admitResolved(peer) + } // Resolve once before parse and unary/streaming branching so both see the same caller. const callerField = method.orchestrationAccess?.caller return needsOrchestrationCallerResolution(rawRequest, callerField) diff --git a/src/main/runtime/terminal/driver/terminal-driver-resources.ts b/src/main/runtime/terminal/driver/terminal-driver-resources.ts index c9655ef980e..3cbe25f462c 100644 --- a/src/main/runtime/terminal/driver/terminal-driver-resources.ts +++ b/src/main/runtime/terminal/driver/terminal-driver-resources.ts @@ -43,6 +43,7 @@ import { RuntimeWorktreeBaseReconciliation } from '../../workspaces/metadata/run import { RuntimeWorktreeRemovalInFlight } from '../../workspaces/removal/runtime-worktree-removal-in-flight' import { ServeBrowserTabs } from '../../browser/headless/serve-browser-tabs' import { readBrowserTabBar } from '../../browser/tabs/browser-tab-listing' +import { readSavedBrowserPageAnnotations } from '../../browser/tabs/browser-tab-annotations' import { parseWorkspaceKey } from '../../../../shared/workspace-scope' import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' import type { ServeBrowserPageState } from '../../browser/headless/serve-browser-tab-layout' @@ -201,6 +202,8 @@ export abstract class OrcaRuntimeWithTerminalDrivers extends OrcaRuntimeWithFitO markHeadlessBrowserSessionTabActive: this.markHeadlessBrowserSessionTabActive.bind(this), notifyHeadlessBrowserSessionTabsChanged: (worktreeId) => this.notifyMobileSessionTabsChanged(worktreeId), + readBrowserPageAnnotations: (browserPageId) => + readSavedBrowserPageAnnotations(this.store, browserPageId), readBrowserTabBar: (worktreeId) => readBrowserTabBar(this.mobileSessionTabsByWorktree, worktreeId, (id) => { // Why: an SSH host's bridged workspace may have no row here, yet its pages render in this window. 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 bdd3a654baa..ab4d4387e4e 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,11 +35,6 @@ vi.mock('../git/command-runner/gh-exec-file', async (importOriginal) => ({ ghExecFileAsync: ghExecFileAsyncMock })) -vi.mock('../git/exec-error', async (importOriginal) => ({ - ...(await importOriginal>()), - extractExecError: vi.fn() -})) - vi.mock('../github/client', () => ({ createGitHubPullRequest: vi.fn(), getRepoSlug: getRepoSlugMock, @@ -71,6 +66,8 @@ vi.mock('./hosted-review', () => ({ import { _resetKnownHostsCache, _resetProjectRefCache } from '../gitlab/gl-utils' import { diagnoseAuth } from '../gitlab/client' import { getHostedReviewCreationEligibility } from './hosted-review-creation' +import { detectHostedReviewProvider } from './forge-provider-detection' +import { rememberGlabKnownHosts } from '../gitlab/gitlab-known-host-probe' function resetMocks(): void { for (const mock of [ @@ -167,4 +164,49 @@ describe('GitLab self-hosted hosted review creation eligibility', () => { blockedReason: null }) }) + + it.each(['per-host failure', 'global inventory', 'remembered inventory'])( + 'keeps GitHub PR identity across repositories despite glab %s', + async (evidence) => { + gitExecFileAsyncMock.mockResolvedValue({ stdout: 'git@github.com:team/orca.git\n' }) + getRepoSlugMock.mockResolvedValue({ owner: 'team', repo: 'orca' }) + if (evidence === 'remembered inventory') { + rememberGlabKnownHosts(['github.com']) + } + glabExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args.includes('--hostname')) { + // Captured glab 1.115 output for a configured host without a token. + throw Object.assign(new Error('glab auth status failed'), { + stdout: '', + stderr: + 'github.com\n x github.com: API call failed\n ! No token found (checked config file, keyring, and environment variables).\n' + }) + } + return { + stdout: + evidence === 'global inventory' + ? 'github.com\n ✓ Logged in to github.com as example-user (config file)\n' + : 'gitlab.com\n ✓ Logged in to gitlab.com as example-user (config file)\n', + stderr: '' + } + }) + for (const repoPath of ['/first-repo', '/second-repo']) { + await expect( + detectHostedReviewProvider({ repoPath, executionHostId: 'local' }) + ).resolves.toBe('github') + } + + gitExecFileAsyncMock.mockResolvedValue({ stdout: 'https://forge.acme.test/team/orca.git\n' }) + glabExecFileAsyncMock.mockRejectedValue( + Object.assign(new Error('glab auth status failed'), { + stdout: '', + stderr: + 'forge.acme.test\n x forge.acme.test: API call failed\n ! No token found (checked config file, keyring, and environment variables).\n' + }) + ) + await expect( + detectHostedReviewProvider({ repoPath: '/custom', executionHostId: 'local' }) + ).resolves.toBe('gitlab') + } + ) }) diff --git a/src/main/window/renderer-publication-throttle-electron-fixture.ts b/src/main/window/renderer-publication-throttle-electron-fixture.ts index 9adaac8227b..3a417f1dc9f 100644 --- a/src/main/window/renderer-publication-throttle-electron-fixture.ts +++ b/src/main/window/renderer-publication-throttle-electron-fixture.ts @@ -47,6 +47,7 @@ async function run(): Promise { maxHeight: 480, everyNthFrame: 1, minFrameIntervalMs: 0, + holdPaint: () => () => {}, onFrame: () => { frames += 1 firstFrame() diff --git a/src/main/workspaces/catalog/imported-folder-project-link.ts b/src/main/workspaces/catalog/imported-folder-project-link.ts new file mode 100644 index 00000000000..022b9f06583 --- /dev/null +++ b/src/main/workspaces/catalog/imported-folder-project-link.ts @@ -0,0 +1,120 @@ +import { getRepoExecutionHostId } from '../../../shared/execution-host' +import { + assertImportedFolderRemoteMatchesProject, + resolveImportedFolderProjectLink +} from '../../../shared/imported-folder-project-identity' +import { + getProjectIdentityKey, + getProjectIdForProviderIdentity, + hasProjectRemoteIdentity +} from '../../../shared/project-host-setup-projection' +import type { ProjectHostSetupExistingFolderArgs } from '../../../shared/project-types' +import type { Repo } from '../../../shared/repo-types' +import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' +import { assertWslMoveHostSetupWritable } from '../../persistence/moving-wsl-projects/wsl-move-scope-guard' +import { readCurrentGitRemoteIdentity } from './repo-git-remote-identity' + +export type RepositoryMetadataOwner = { + enqueueRepositoryMetadata: (repos: readonly Repo[]) => void + resolveRepositoryMetadata: (repo: Repo) => Promise +} + +export async function linkImportedFolderToProject( + getStore: () => RuntimeStore | null, + initialRepo: Repo, + folderRemote: Pick, + args: ProjectHostSetupExistingFolderArgs, + metadata: RepositoryMetadataOwner +): Promise { + const store = getStore() + if (!store) { + throw new Error('runtime_unavailable') + } + const currentRow = (): Repo => { + const repo = store + .getRepos() + .find( + (entry) => + entry.id === initialRepo.id && + getRepoExecutionHostId(entry) === getRepoExecutionHostId(initialRepo) + ) + if ( + getStore() !== store || + !repo || + repo.path !== initialRepo.path || + repo.kind !== initialRepo.kind + ) { + throw new Error(`Project setup repo disappeared before it could be linked: ${initialRepo.id}`) + } + assertWslMoveHostSetupWritable(store, { + projectId: args.projectId, + hostId: getRepoExecutionHostId(repo), + repoId: repo.id + }) + return repo + } + const project = store.getProjects?.().find((entry) => entry.id === args.projectId) + const provider = project?.providerIdentity ?? args.projectProviderIdentity + const selectedProvider = + provider && getProjectIdForProviderIdentity(provider) === args.projectId ? provider : undefined + let repo = currentRow() + // Legacy icon-only matches keep their existing acceptance without a new probe or stamp. + const legacyMatch = + getProjectIdentityKey(repo) === args.projectId && + repo.repoIcon?.type === 'image' && + repo.repoIcon.source === 'github' && + !hasProjectRemoteIdentity({ gitRemoteIdentity: folderRemote.gitRemoteIdentity }) + const needsEvidence = !!selectedProvider && repo.upstream === undefined && !legacyMatch + let metadataFinished = false + if (needsEvidence) { + metadataFinished = await metadata.resolveRepositoryMetadata(repo) + repo = currentRow() + folderRemote = await readCurrentGitRemoteIdentity({ ...repo, ...folderRemote }) + repo = currentRow() + } + const updates: Partial = { + projectHostSetupMethod: args.setupMethod ?? 'imported-existing-folder' + } + const keepsCurrentIdentity = + repo.upstream !== undefined && getProjectIdentityKey(repo) === args.projectId + if (needsEvidence && !keepsCurrentIdentity) { + updates.gitRemoteIdentity = folderRemote.gitRemoteIdentity + } + const candidate = { ...repo, ...updates } + const projectedId = getProjectIdentityKey(candidate) + if ( + projectedId === args.projectId && + needsEvidence && + repo.upstream === undefined && + selectedProvider + ) { + assertImportedFolderRemoteMatchesProject(folderRemote, selectedProvider) + } + if (projectedId !== args.projectId) { + Object.assign( + updates, + resolveImportedFolderProjectLink( + { ...candidate, ...folderRemote }, + args.projectId, + selectedProvider + ) + ) + } else if (needsEvidence && repo.upstream === undefined) { + // This successful explicit origin choice is terminal; ordinary failed probes stay unknown. + updates.upstream = null + } + if (getProjectIdentityKey({ ...repo, ...updates }) !== args.projectId) { + throw new Error('Imported folder does not match the selected project identity.') + } + const updated = store.updateRepo(repo, updates) + if (!updated) { + throw new Error(`Project setup repo disappeared before it could be linked: ${repo.id}`) + } + if (getProjectIdentityKey(updated) !== args.projectId) { + throw new Error('Imported folder does not match the selected project identity.') + } + if (!needsEvidence || !metadataFinished) { + metadata.enqueueRepositoryMetadata([updated]) + } + return updated +} diff --git a/src/main/workspaces/catalog/repo-backfill-wsl-move.test.ts b/src/main/workspaces/catalog/repo-backfill-wsl-move.test.ts index 3e6cee6b328..97457fb3d2c 100644 --- a/src/main/workspaces/catalog/repo-backfill-wsl-move.test.ts +++ b/src/main/workspaces/catalog/repo-backfill-wsl-move.test.ts @@ -26,7 +26,7 @@ vi.mock('electron', () => ({ })) vi.mock('./repo-git-remote-identity', () => ({ probeGitRemoteIdentity: vi.fn() })) vi.mock('../../github/client/fetch/repo-slug-upstream', () => ({ - getRepoUpstream: vi.fn(async () => ({ owner: 'acme', repo: 'app' })) + probeRepoUpstream: vi.fn(async () => ({ upstream: { owner: 'acme', repo: 'app' }, origin: null })) })) vi.mock('../../repository-icons/repo-icon-autodetect', () => ({ detectGitHubAvatarIcon: vi.fn(async () => null) diff --git a/src/renderer/src/app-shell/AppWorkspaceShell.tsx b/src/renderer/src/app-shell/AppWorkspaceShell.tsx index 2e038a6e551..4a54bbfedc4 100644 --- a/src/renderer/src/app-shell/AppWorkspaceShell.tsx +++ b/src/renderer/src/app-shell/AppWorkspaceShell.tsx @@ -4,7 +4,7 @@ import { useTranslate } from '@/i18n/use-translate' import { useAppStore } from '@/store/index' import { usePluginViewCaptureStore } from '@/store/plugins/capture/plugin-view-capture' import { pendingCreationOpensNativeChat } from '@/lib/workspace/creation/pending-worktree-creation' -import { showsFloatingRightSidebarToggle } from '@/lib/right-sidebar-visibility' +import { showsFloatingRightSidebarToggle } from '@/components/right-sidebar/visibility/right-sidebar-visibility' import Sidebar from '../components/Sidebar' import RightSidebar from '../components/right-sidebar/index' import { RecoverableRenderErrorBoundary } from '../components/error-boundaries/RecoverableRenderErrorBoundary' diff --git a/src/renderer/src/app-shell/TitlebarLeftControls.tsx b/src/renderer/src/app-shell/TitlebarLeftControls.tsx index 368782096ad..0213a23351b 100644 --- a/src/renderer/src/app-shell/TitlebarLeftControls.tsx +++ b/src/renderer/src/app-shell/TitlebarLeftControls.tsx @@ -8,13 +8,13 @@ import { ContextMenuItem, ContextMenuTrigger } from '@/components/ui/context-menu' -import { shouldShowWorktreeHistoryControls } from '../lib/titlebar-worktree-history-controls' +import { shouldShowWorktreeHistoryControls } from './chrome/titlebar-worktree-history-controls' import { canGoBackWorktreeHistory, canGoForwardWorktreeHistory } from '@/store/slices/ui/workspace-navigation-history' import { useShortcutLabel } from '../hooks/useShortcutLabel' -import { useAppStore } from '../store' +import { useAppStore } from '../store/index' import { hasCustomTitleBar, hasMacTrafficLights } from './app-window-chrome' import type { AppChromeLayout } from './use-app-chrome-layout' diff --git a/src/renderer/src/app-shell/app-command-handlers-tab-rename.test.ts b/src/renderer/src/app-shell/app-command-handlers-tab-rename.test.ts deleted file mode 100644 index 566ec19a254..00000000000 --- a/src/renderer/src/app-shell/app-command-handlers-tab-rename.test.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { Tab, TabGroup } from '../../../shared/tab-types' -import type { TerminalTab } from '../../../shared/workspace-layout/terminal-tab-types' -import type { AppState } from '@/store/types' -import { createTabsFocusActions } from '../store/slices/tabs/tabs-focus-actions' -import type { TabsSliceGet, TabsSliceSet } from '../store/slices/tabs/tabs-slice-contract' -import { buildActiveSurfacePatch } from '../store/slices/tabs/tabs-surface' - -const mocks = vi.hoisted(() => ({ - requestTerminalTabRename: vi.fn(), - store: {} as AppState -})) - -vi.mock('../store', () => ({ - useAppStore: Object.assign(vi.fn(), { getState: () => mocks.store }) -})) - -vi.mock('../components/tab-bar/terminal-tab-rename-request', () => ({ - requestTerminalTabRename: mocks.requestTerminalTabRename -})) - -vi.mock('@/components/floating-terminal/floating-workspace-terminal-actions', () => ({ - isFloatingWorkspacePanelFocused: () => false -})) - -vi.mock('@/lib/terminal-shortcut-capture-notification', () => ({ - showTerminalShortcutCaptureNotification: vi.fn() -})) - -import { - type AppShortcutState, - type ShortcutDispatchInput, - createAppCommandHandlers -} from './app-command-handlers' - -const WORKTREE_ID = 'repo::/feature' -const GROUP_ID = 'group-1' -const TERMINAL_ENTITY_ID = 'terminal-1' -const TERMINAL_UNIFIED_ID = 'unified-terminal' -const CHAT_UNIFIED_ID = 'unified-chat' - -function unifiedTab(overrides: Partial & Pick): Tab { - return { - groupId: GROUP_ID, - worktreeId: WORKTREE_ID, - label: overrides.id, - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 0, - ...overrides - } -} - -/** Derive active surfaces as the real store does: structured-chat focus leaves activeTabId on the last terminal. Stubbing it would hide the rename defect. */ -function storeForActiveTab(activeGroupTabId: string): AppState { - const groups: TabGroup[] = [ - { - id: GROUP_ID, - worktreeId: WORKTREE_ID, - activeTabId: activeGroupTabId, - tabOrder: [TERMINAL_UNIFIED_ID, CHAT_UNIFIED_ID] - } - ] - const rawState = { - activeBrowserTabIdByWorktree: {}, - activeFileIdByWorktree: {}, - activeGroupIdByWorktree: { [WORKTREE_ID]: GROUP_ID }, - // The user focused this terminal before switching to the structured tab. - activeTabIdByWorktree: { [WORKTREE_ID]: TERMINAL_ENTITY_ID }, - activeTabTypeByWorktree: {}, - browserTabsByWorktree: {}, - groupsByWorktree: { [WORKTREE_ID]: groups }, - layoutByWorktree: {}, - openFiles: [], - tabsByWorktree: { - [WORKTREE_ID]: [{ id: TERMINAL_ENTITY_ID, worktreeId: WORKTREE_ID } as TerminalTab] - }, - unifiedTabsByWorktree: { - [WORKTREE_ID]: [ - unifiedTab({ - id: TERMINAL_UNIFIED_ID, - entityId: TERMINAL_ENTITY_ID, - contentType: 'terminal' - }), - unifiedTab({ id: CHAT_UNIFIED_ID, entityId: 'session-1', contentType: 'agent-session' }) - ] - } - } as unknown as AppState - const store = { - ...rawState, - ...buildActiveSurfacePatch(rawState, WORKTREE_ID) - } as AppState - const noopSet = (() => {}) as unknown as TabsSliceSet - store.getActiveTab = createTabsFocusActions(noopSet, (() => store) as TabsSliceGet).getActiveTab - return store -} - -function shortcutState(): AppShortcutState { - return { - activeView: 'terminal', - activeWorktreeId: WORKTREE_ID, - actions: {} as AppShortcutState['actions'], - creationLayoutActive: false, - floatingTerminalEnabled: false, - floatingTerminalOpen: false, - floatingVisibleTabCount: 0, - keybindings: {}, - openFloatingWorkspaceMaximized: vi.fn(), - pluginCommands: [], - setFloatingTerminalOpen: vi.fn(), - terminalShortcutPolicy: 'orca-first', - workspaceChromeActive: true - } -} - -function shortcutInput(): ShortcutDispatchInput { - return { target: null, defaultPrevented: false, preventDefault: vi.fn() } -} - -function runRename(state: AppShortcutState = shortcutState()): boolean | undefined { - return createAppCommandHandlers(state, shortcutInput(), 'terminal').get('tab.rename')?.() -} - -describe('tab.rename shortcut', () => { - beforeEach(() => vi.clearAllMocks()) - - it('renames the structured chat tab, not the stale background terminal', () => { - mocks.store = storeForActiveTab(CHAT_UNIFIED_ID) - expect(runRename()).toBe(true) - expect(mocks.requestTerminalTabRename).toHaveBeenCalledWith(CHAT_UNIFIED_ID) - expect(mocks.requestTerminalTabRename).not.toHaveBeenCalledWith(TERMINAL_ENTITY_ID) - }) -}) diff --git a/src/renderer/src/app-shell/app-command-handlers.ts b/src/renderer/src/app-shell/app-command-handlers.ts index 22807ffc08f..5761fd34574 100644 --- a/src/renderer/src/app-shell/app-command-handlers.ts +++ b/src/renderer/src/app-shell/app-command-handlers.ts @@ -1,11 +1,11 @@ -import { canShowRightSidebarForView, canToggleRightSidebar } from '@/lib/right-sidebar-visibility' -import { runBuiltInOrReplacement } from '@/lib/plugin-command-replacements' +import { canShowRightSidebarForView } from '@/components/right-sidebar/visibility/right-sidebar-visibility' +import { runBuiltInOrReplacement } from '@/lib/plugins/commands/plugin-command-replacements' import { isFloatingWorkspacePanelFocused } from '@/components/floating-terminal/floating-workspace-terminal-actions' import { hasVisibleOverlay } from '@/lib/visible-overlay' -import { requestScrollToCurrentWorkspaceRevealAndRename } from '@/lib/scroll-to-current-workspace-status' +import { requestScrollToCurrentWorkspaceRevealAndRename } from '@/lib/workspace/navigation/scroll-to-current-workspace-status' import { requestVirtualizedScrollAnchorRecord } from '@/hooks/requestVirtualizedScrollAnchorRecord' -import { showTerminalShortcutCaptureNotification } from '@/lib/terminal-shortcut-capture-notification' -import { shouldShowWorktreeHistoryControls } from '../lib/titlebar-worktree-history-controls' +import { showTerminalShortcutCaptureNotification } from '@/lib/notifications/terminal-shortcut-capture-notification' +import { shouldShowWorktreeHistoryControls } from './chrome/titlebar-worktree-history-controls' import { TOGGLE_WORKSPACE_BOARD_EVENT } from '../components/sidebar/workspace-board/surface/useWorkspaceBoardPanel' import { getRenderedLineageChipKeys, @@ -13,9 +13,9 @@ import { } from '../components/sidebar/workspace-card/identity/child-workspaces-toggle-target' import { requestTerminalTabRename } from '../components/tab-bar/terminal-tab-rename-request' import { - deleteHoveredWorkspaceImmediately, - resolveHoveredWorkspaceDeleteTarget -} from '../components/sidebar/workspace-actions/deletion/hovered-workspace-delete' + 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' @@ -230,12 +230,12 @@ export function createAppCommandHandlers( return false } const store = useAppStore.getState() - const target = resolveHoveredWorkspaceDeleteTarget(store) + const target = resolveActiveWorkspaceDeleteTarget(store) if (!target) { return false } return claim('workspace.delete', () => { - deleteHoveredWorkspaceImmediately(store, target) + deleteActiveWorkspaceFromShortcut(store, target) }) } ], @@ -270,7 +270,7 @@ export function createAppCommandHandlers( [ 'sidebar.right.toggle', () => - canToggleRightSidebar(activeView) + canShowRightSidebarForView(activeView) ? claim('sidebar.right.toggle', () => actions.toggleRightSidebar()) : false ], diff --git a/src/renderer/src/app-shell/app-window-chrome.ts b/src/renderer/src/app-shell/app-window-chrome.ts index 9cba84dee1b..16038d5c244 100644 --- a/src/renderer/src/app-shell/app-window-chrome.ts +++ b/src/renderer/src/app-shell/app-window-chrome.ts @@ -1,7 +1,7 @@ import { isPairedWebClientWindow, shouldRenderDesktopWindowChrome -} from '@/lib/desktop-window-chrome' +} from '@/app-shell/chrome/desktop-window-chrome' export const isMac = navigator.userAgent.includes('Mac') const isWindows = !isMac && navigator.userAgent.includes('Windows') diff --git a/src/renderer/src/app-shell/appearance/terminal-app-theme.ts b/src/renderer/src/app-shell/appearance/terminal-app-theme.ts index 32dc7c0e44a..b638a1dc940 100644 --- a/src/renderer/src/app-shell/appearance/terminal-app-theme.ts +++ b/src/renderer/src/app-shell/appearance/terminal-app-theme.ts @@ -1,31 +1,22 @@ -import type { ITheme } from '@xterm/xterm' -import type { GlobalSettings } from '../../../../shared/global-settings-types' -import { - completePluginAppThemeTokens, - type PluginThemeTokenColorRule -} from '../../../../shared/plugins/artifacts/plugin-theme-artifact' +import { completePluginAppThemeTokens } from '../../../../shared/plugins/artifacts/plugin-theme-artifact' +import type { PluginThemeTokenColorRule } from '../../../../shared/plugins/artifacts/plugin-theme-artifact' import { pluginAppThemeCssFallback } from '../../../../shared/plugins/artifacts/plugin-theme-css-fallbacks' import { MATCH_TERMINAL_APP_THEME } from '../../../../shared/plugin-theme-settings' -import { - resolveTerminalPalette, - type TerminalPaletteSettings as TerminalAppThemeSettings -} from '../../../../shared/terminal-themes/terminal-theme-selection' -import type { AppThemePaint } from './document-theme' +import { resolveTerminalPalette } from '../../../../shared/terminal-themes/terminal-theme-selection' +import type { TerminalPaletteSettings as TerminalAppThemeSettings } from '../../../../shared/terminal-themes/terminal-theme-selection' import { hashThemeContent } from '../../lib/editor/appearance/plugin-monaco-theme' -import type { ColorProbe } from './plugin-theme-tokens' -import { - contrastRatio, - mix, - readableOn, - rgbaToHex, - type Rgba -} from '../../../../shared/color/rgba-contrast' -import { getSystemPrefersDark } from '../../lib/terminal-theme' +import { contrastRatio, mix, readableOn, rgbaToHex } from '../../../../shared/color/rgba-contrast' +import type { Rgba } from '../../../../shared/color/rgba-contrast' +import { getSystemPrefersDark } from '../../lib/terminal/appearance/terminal-theme' import { isTerminalBackgroundLight, resolveOpaqueTerminalBackground } from '../../../../shared/terminal-themes/terminal-title-contrast' import { terminalPaletteRgba } from '../../../../shared/terminal-themes/terminal-palette-rgba' +import type { ITheme } from '@xterm/xterm' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import type { AppThemePaint } from './document-theme' +import type { ColorProbe } from './plugin-theme-tokens' export type TerminalAppTheme = AppThemePaint & { id: typeof MATCH_TERMINAL_APP_THEME diff --git a/src/renderer/src/lib/desktop-window-chrome.ts b/src/renderer/src/app-shell/chrome/desktop-window-chrome.ts similarity index 100% rename from src/renderer/src/lib/desktop-window-chrome.ts rename to src/renderer/src/app-shell/chrome/desktop-window-chrome.ts diff --git a/src/renderer/src/lib/titlebar-left-chrome.ts b/src/renderer/src/app-shell/chrome/titlebar-left-chrome.ts similarity index 100% rename from src/renderer/src/lib/titlebar-left-chrome.ts rename to src/renderer/src/app-shell/chrome/titlebar-left-chrome.ts diff --git a/src/renderer/src/lib/titlebar-worktree-history-controls.ts b/src/renderer/src/app-shell/chrome/titlebar-worktree-history-controls.ts similarity index 100% rename from src/renderer/src/lib/titlebar-worktree-history-controls.ts rename to src/renderer/src/app-shell/chrome/titlebar-worktree-history-controls.ts diff --git a/src/renderer/src/lib/ui-zoom.ts b/src/renderer/src/app-shell/chrome/ui-zoom.ts similarity index 94% rename from src/renderer/src/lib/ui-zoom.ts rename to src/renderer/src/app-shell/chrome/ui-zoom.ts index 654e4476c39..d12e09fc1e0 100644 --- a/src/renderer/src/lib/ui-zoom.ts +++ b/src/renderer/src/app-shell/chrome/ui-zoom.ts @@ -1,4 +1,4 @@ -import { uiZoomFactorFromLevel } from '../../../shared/ui-zoom-level' +import { uiZoomFactorFromLevel } from '../../../../shared/ui-zoom-level' const isMac = navigator.userAgent.includes('Mac') diff --git a/src/renderer/src/lib/zoom-events.ts b/src/renderer/src/app-shell/chrome/zoom-events.ts similarity index 100% rename from src/renderer/src/lib/zoom-events.ts rename to src/renderer/src/app-shell/chrome/zoom-events.ts diff --git a/src/renderer/src/app-shell/platform/paired-web-client-host.ts b/src/renderer/src/app-shell/platform/paired-web-client-host.ts index af617064ec0..3a05d6b673c 100644 --- a/src/renderer/src/app-shell/platform/paired-web-client-host.ts +++ b/src/renderer/src/app-shell/platform/paired-web-client-host.ts @@ -3,7 +3,7 @@ import { toRuntimeExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' -import { isPairedWebClientWindow } from '../../lib/desktop-window-chrome' +import { isPairedWebClientWindow } from '../chrome/desktop-window-chrome' type HostRouteState = { runtimeEnvironments?: readonly { id: string }[] } diff --git a/src/renderer/src/app-shell/plugin-settings-shortcut-handler.ts b/src/renderer/src/app-shell/plugin-settings-shortcut-handler.ts index 6892d4d237a..27b4a41b13d 100644 --- a/src/renderer/src/app-shell/plugin-settings-shortcut-handler.ts +++ b/src/renderer/src/app-shell/plugin-settings-shortcut-handler.ts @@ -1,4 +1,4 @@ -import { isPairedWebClientWindow } from '@/lib/desktop-window-chrome' +import { isPairedWebClientWindow } from '@/app-shell/chrome/desktop-window-chrome' import { isEditableTarget, isNativeChatPromptTarget } from '@/lib/text-input/focus/editable-target' export function createPluginsSettingsShortcutHandler( diff --git a/src/renderer/src/lib/indexeddb-connection.ts b/src/renderer/src/app-shell/storage/indexeddb-connection.ts similarity index 100% rename from src/renderer/src/lib/indexeddb-connection.ts rename to src/renderer/src/app-shell/storage/indexeddb-connection.ts diff --git a/src/renderer/src/app-shell/use-app-chrome-layout.ts b/src/renderer/src/app-shell/use-app-chrome-layout.ts index 74fc1ac1652..a01341d6f6b 100644 --- a/src/renderer/src/app-shell/use-app-chrome-layout.ts +++ b/src/renderer/src/app-shell/use-app-chrome-layout.ts @@ -1,11 +1,11 @@ import { useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' import { useShallow } from 'zustand/react/shallow' import { SYNC_FIT_PANES_EVENT } from '@/constants/terminal' -import { canShowRightSidebarForView } from '@/lib/right-sidebar-visibility' +import { canShowRightSidebarForView } from '@/components/right-sidebar/visibility/right-sidebar-visibility' import { resolveLeftSidebarStyleVariables } from '@/app-shell/appearance/left-sidebar-appearance' -import { resolveLeftTitlebarChromeLayout } from '@/lib/titlebar-left-chrome' +import { resolveLeftTitlebarChromeLayout } from '@/app-shell/chrome/titlebar-left-chrome' import { selectWorktreeCreationSurfaceShown } from '@/lib/workspace/creation/worktree-creation-surface' -import { useAppStore } from '../store' +import { useAppStore } from '../store/index' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' import { selectActiveTerminalChromeState } from './active-terminal-chrome-selector' import { diff --git a/src/renderer/src/app-shell/use-app-session-persistence.ts b/src/renderer/src/app-shell/use-app-session-persistence.ts index 9fca4439f46..fce1c24e754 100644 --- a/src/renderer/src/app-shell/use-app-session-persistence.ts +++ b/src/renderer/src/app-shell/use-app-session-persistence.ts @@ -20,7 +20,7 @@ import { createShutdownCheckpointGuard } from './shutdown/shutdown-checkpoint-guard' import { showShutdownCheckpointFailureToast } from './shutdown/shutdown-checkpoint-failure-toast' -import { isPairedWebClientWindow } from '../lib/desktop-window-chrome' +import { isPairedWebClientWindow } from './chrome/desktop-window-chrome' import { createShutdownCheckpointPersist } from './shutdown-checkpoint-persist' import { shutdownBufferCaptures } from '../components/terminal-pane/snapshots/shutdown-buffer-captures' import { diff --git a/src/renderer/src/app-shell/use-app-startup-hydration.ts b/src/renderer/src/app-shell/use-app-startup-hydration.ts index f8aa1abb34d..1e388fc3bc6 100644 --- a/src/renderer/src/app-shell/use-app-startup-hydration.ts +++ b/src/renderer/src/app-shell/use-app-startup-hydration.ts @@ -1,7 +1,7 @@ import { restoreStructuredLaunchSurfaces } from '@/lib/agent-session/launch/structured-agent-session-launch-surface' import { useEffect, useRef } from 'react' import { restoreLocalStructuredChatsAtStartup } from '@/runtime/native-chat/local-sessions/local-structured-chats' -import { syncZoomCSSVar } from '@/lib/ui-zoom' +import { syncZoomCSSVar } from '@/app-shell/chrome/ui-zoom' import { installCodexDetachedPaneRestartExecutor } from '@/components/terminal-pane/account-restart/detached/codex-detached-pane-restart-scheduler' import { useAppStore } from '../store/index' import { reconcileHydratedWorkspaceTabModels } from './reconcile-hydrated-workspace-tab-models' @@ -24,7 +24,7 @@ import { recoverFromDegradedStartup } from '../startup/startup-degraded-recovery import { restoreSshConnectionsForStartup } from '../startup/startup-ssh-connection-restore' import { collectActiveWorkspaceSshTargetIds } from '../startup/active-workspace-ssh-targets' import { publishTerminalViewAttributesAtAppStart } from '../components/terminal-pane/appearance/terminal-appearance' -import { getSystemPrefersDark } from '../lib/terminal-theme' +import { getSystemPrefersDark } from '../lib/terminal/appearance/terminal-theme' import { collectTerminalProviderSnapshotPtyIds, refreshTerminalProviderSnapshotCapabilities @@ -40,12 +40,12 @@ import { listRuntimeSessionHostsForStartup } from './startup-runtime-session-hos import { mapWithConcurrency } from '../../../shared/map-with-concurrency' import { collectWslMovedWorkspaceKeysFromSession } from '../store/repos/wsl-moved-projects' import { wslMovedSessionReadApi } from '../store/repos/wsl-moved-local-session-rows' -import type { OnboardingState } from '../../../shared/onboarding-state-types' import { ensureLocalRuntimeCapabilities } from '../runtime/hosts/capabilities/local-runtime-capabilities' import { finishStartupWorktreeHydration, refreshStartupWorktrees } from '../startup/startup-worktree-refresh' +import type { OnboardingState } from '../../../shared/onboarding-state-types' /** Hydrate settings/UI/catalog/session, reconnect and restore terminals before unlocking saves. Failure boots in degraded no-save mode to protect disk state. */ export function useAppStartupHydration(onOnboardingLoaded: (state: OnboardingState) => void): void { diff --git a/src/renderer/src/app-shell/use-document-appearance.ts b/src/renderer/src/app-shell/use-document-appearance.ts index a8b0ff240cf..44ed5a220e7 100644 --- a/src/renderer/src/app-shell/use-document-appearance.ts +++ b/src/renderer/src/app-shell/use-document-appearance.ts @@ -99,6 +99,12 @@ export function useDocumentAppearance(): void { usePluginFontRegistration() const reduceEffects = useReduceVisualEffects(useAppStore((s) => s.settings?.reduceVisualEffects)) const surfaceOpacity = useAppStore((s) => s.settings?.terminalBackgroundOpacity ?? 1) + useEffect(() => { + document.documentElement.style.setProperty( + '--orca-window-surface-opacity', + String(surfaceOpacity) + ) + }, [surfaceOpacity]) // Why re-parse: the theme list keeps the registration as received, and a newer host may send // a background this build cannot paint; it must drop to no image, never reach CSS. const registeredBackground = pluginTheme?.background diff --git a/src/renderer/src/app-shell/use-global-keybindings.ts b/src/renderer/src/app-shell/use-global-keybindings.ts index 62c6718798c..4ea218e6480 100644 --- a/src/renderer/src/app-shell/use-global-keybindings.ts +++ b/src/renderer/src/app-shell/use-global-keybindings.ts @@ -1,23 +1,23 @@ import { useEffect, useLayoutEffect, useRef } from 'react' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' -import { canShowRightSidebarForView } from '@/lib/right-sidebar-visibility' +import { canShowRightSidebarForView } from '@/components/right-sidebar/visibility/right-sidebar-visibility' import { getSelectedTextForFileSearch } from '../lib/files/search/file-search-selection' import { registerAppCommandDispatcher } from '@/lib/app-commands/app-command-dispatch' -import { executePluginCommand } from '@/lib/plugin-command-execution' -import { runBuiltInOrReplacement } from '@/lib/plugin-command-replacements' +import { executePluginCommand } from '@/lib/plugins/commands/plugin-command-execution' +import { runBuiltInOrReplacement } from '@/lib/plugins/commands/plugin-command-replacements' import { findPluginCommandForKeybinding, globalShortcutTargetYields -} from '@/lib/plugin-command-keybindings' +} from '@/lib/plugins/commands/plugin-command-keybindings' import { shouldMinimizeFloatingWorkspacePanelOnCloseShortcut } from '@/components/floating-terminal/floating-workspace-terminal-actions' -import { showTerminalShortcutCaptureNotification } from '@/lib/terminal-shortcut-capture-notification' +import { showTerminalShortcutCaptureNotification } from '@/lib/notifications/terminal-shortcut-capture-notification' import { folderRelativePathToIncludeGlob, selectedExplorerFolderRelativePath } from '../components/right-sidebar/file-explorer/content-search/file-search-include-pattern' import { usePluginCommands } from '@/store/plugins/catalog/plugin-contribution-catalog' -import { useAppStore } from '../store' +import { useAppStore } from '../store/index' import { keybindingMatchesAction, type KeybindingActionId } from '../../../shared/keybindings' import { PLUGIN_COMMAND_ALIAS_ACTION_IDS } from '../../../shared/plugins/contributions/plugin-command-actions' import { diff --git a/src/renderer/src/app-shell/use-terminal-viewer-color-publication.ts b/src/renderer/src/app-shell/use-terminal-viewer-color-publication.ts index c510b7304e1..89875c6d7b0 100644 --- a/src/renderer/src/app-shell/use-terminal-viewer-color-publication.ts +++ b/src/renderer/src/app-shell/use-terminal-viewer-color-publication.ts @@ -1,9 +1,9 @@ import { useEffect } from 'react' -import { getSystemPrefersDark } from '@/lib/terminal-theme' +import { getSystemPrefersDark } from '@/lib/terminal/appearance/terminal-theme' import { publishTerminalViewAttributesAtAppStart } from '../components/terminal-pane/appearance/terminal-appearance' import { subscribeToPublishedTerminalViewAttributes } from '../components/terminal-pane/appearance/terminal-view-attributes-publisher' import { remoteRuntimeTerminalColorPush } from '../runtime/hosted-terminals/streams/remote-runtime-terminal-color-push' -import { useAppStore } from '../store' +import { useAppStore } from '../store/index' /** Reports this window's terminal theme to its own host and to every paired host. */ export function useTerminalViewerColorPublication(): void { diff --git a/src/renderer/src/app-shell/use-visible-review-refresh-reporting.ts b/src/renderer/src/app-shell/use-visible-review-refresh-reporting.ts index 273779d34ed..e80c181e486 100644 --- a/src/renderer/src/app-shell/use-visible-review-refresh-reporting.ts +++ b/src/renderer/src/app-shell/use-visible-review-refresh-reporting.ts @@ -1,7 +1,7 @@ import { useEffect, useMemo, useRef } from 'react' -import { useAppStore } from '../store' +import { useAppStore } from '../store/index' import type { AppState } from '../store/types' -import { rightSidebarShowsPullRequestData } from '../lib/right-sidebar-visibility' +import { rightSidebarShowsPullRequestData } from '../components/right-sidebar/visibility/right-sidebar-visibility' import { findWorktreeById, buildPRRefreshCandidate } from '../store/github/refresh/worktree-refresh' import { getHostedReviewCacheKey } from '../store/slices/hosted-review/hosted-review-cache-identity' import { getVisibleHostedReviewWorkspaces } from '../store/slices/hosted-review/refresh/visible-hosted-review-refresh-targets' diff --git a/src/renderer/src/app-shell/use-window-visibility-effects.ts b/src/renderer/src/app-shell/use-window-visibility-effects.ts index 788a1b93a94..7f39209ffe6 100644 --- a/src/renderer/src/app-shell/use-window-visibility-effects.ts +++ b/src/renderer/src/app-shell/use-window-visibility-effects.ts @@ -1,6 +1,6 @@ import { useEffect } from 'react' -import { isPairedWebClientWindow } from '@/lib/desktop-window-chrome' -import { useAppStore } from '../store' +import { isPairedWebClientWindow } from '@/app-shell/chrome/desktop-window-chrome' +import { useAppStore } from '../store/index' import { isMac } from './app-window-chrome' import { selectWindowVisibilityActions } from './window-visibility-actions-selector' diff --git a/src/renderer/src/attention/agent-attention-notification-delivery.ts b/src/renderer/src/attention/agent-attention-notification-delivery.ts index edbd09548e8..09ba0c16157 100644 --- a/src/renderer/src/attention/agent-attention-notification-delivery.ts +++ b/src/renderer/src/attention/agent-attention-notification-delivery.ts @@ -1,6 +1,6 @@ /** Share delivery, success sound and blocked-permission fallback across surfaces; callers own message content. Main applies banner preferences after mobile fanout, so callers cannot promise a banner. */ -import { playDesktopNotificationSound } from '@/lib/desktop-notification-sound' -import { showBlockedNotificationFallbackToast } from '@/lib/blocked-notification-fallback' +import { playDesktopNotificationSound } from '@/lib/notifications/desktop-notification-sound' +import { showBlockedNotificationFallbackToast } from '@/lib/notifications/blocked-notification-fallback' import type { NotificationDispatchRequest, NotificationDispatchResult diff --git a/src/renderer/src/attention/notification-workspace-labels.ts b/src/renderer/src/attention/notification-workspace-labels.ts index b86c6836f1a..0eb04646b92 100644 --- a/src/renderer/src/attention/notification-workspace-labels.ts +++ b/src/renderer/src/attention/notification-workspace-labels.ts @@ -5,7 +5,7 @@ import { worktreeHostMatchOptions, worktreeMatchesHost } from '../store/slices/worktrees/listing/worktree-host-ownership' -import { getResolvedExecutionHostIdForWorktree } from '../lib/resolved-worktree-execution-host' +import { getResolvedExecutionHostIdForWorktree } from '../lib/workspace/ownership/resolved-worktree-execution-host' import { getActiveWorkspaceExecutionHostId } from '../lib/workspace/ownership/active-workspace-host' import { findIndexedFolderWorkspaceOwner, diff --git a/src/renderer/src/lib/unread-badge-count-selector.test.ts b/src/renderer/src/attention/unread/unread-badge-count-selector.test.ts similarity index 97% rename from src/renderer/src/lib/unread-badge-count-selector.test.ts rename to src/renderer/src/attention/unread/unread-badge-count-selector.test.ts index 192b0a80b1c..0e12c92abff 100644 --- a/src/renderer/src/lib/unread-badge-count-selector.test.ts +++ b/src/renderer/src/attention/unread/unread-badge-count-selector.test.ts @@ -5,9 +5,9 @@ import { makeTab } from '@/store/terminals/terminal-tab.test-fixture' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' import { TEST_REPO } from '@/store/repos/repo.test-fixture' import { makeFolderWorkspace } from '@/store/folder-workspaces/folder-workspace.test-fixture' -import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' -import type { ProjectGroup } from '../../../shared/project-group-types' -import { folderWorkspaceKey } from '../../../shared/workspace-scope' +import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' +import type { ProjectGroup } from '../../../../shared/project-group-types' +import { folderWorkspaceKey } from '../../../../shared/workspace-scope' import { createUnreadBadgeCountSelector } from './unread-badge-count-selector' // Why: marking a folder workspace unread persists through this API; echo the write back. diff --git a/src/renderer/src/lib/unread-badge-count-selector.ts b/src/renderer/src/attention/unread/unread-badge-count-selector.ts similarity index 92% rename from src/renderer/src/lib/unread-badge-count-selector.ts rename to src/renderer/src/attention/unread/unread-badge-count-selector.ts index 7c64dd39656..57849f62608 100644 --- a/src/renderer/src/lib/unread-badge-count-selector.ts +++ b/src/renderer/src/attention/unread/unread-badge-count-selector.ts @@ -1,13 +1,13 @@ import { getVisibleWorkspaceHostIdSet } from '@/components/sidebar/worktree-list/listing/visible-worktree-host-scope' -import { getPairedDeviceIdsByEnvironment } from '../../../shared/workspace-creator-visibility' +import { getPairedDeviceIdsByEnvironment } from '../../../../shared/workspace-creator-visibility' import { getIndexedRepoMap } from '@/store/repos/repository-catalog-index' import type { AppState } from '@/store/types' -import { getSettingsFocusedExecutionHostId } from '../../../shared/execution-host' -import type { Worktree } from '../../../shared/worktree/types' -import { sameBucketRecords } from './bucket-record-equality' +import { getSettingsFocusedExecutionHostId } from '../../../../shared/execution-host' +import type { Worktree } from '../../../../shared/worktree/types' +import { sameBucketRecords } from '../../lib/bucket-record-equality' import { getUnreadBadgeCount } from './unread-badge-count' import { hasLiveTabMarker } from '@/store/slices/workspace-attention/workspace-live-markers' -import { folderWorkspaceKey } from '../../../shared/workspace-scope' +import { folderWorkspaceKey } from '../../../../shared/workspace-scope' import { selectFolderWorkspaces, selectWorktreesByRepo diff --git a/src/renderer/src/lib/unread-badge-count.ts b/src/renderer/src/attention/unread/unread-badge-count.ts similarity index 79% rename from src/renderer/src/lib/unread-badge-count.ts rename to src/renderer/src/attention/unread/unread-badge-count.ts index 1e1fd1f0c4e..9266b72d38f 100644 --- a/src/renderer/src/lib/unread-badge-count.ts +++ b/src/renderer/src/attention/unread/unread-badge-count.ts @@ -1,22 +1,22 @@ import { filterFolderWorkspacesForVisibleHosts, filterProjectGroupsForVisibleHosts -} from '../../../shared/sidebar-list/host-filtering' -import { getRenderableFolderWorkspaces } from '../../../shared/sidebar-list/folder-workspace-lanes' +} from '../../../../shared/sidebar-list/host-filtering' +import { getRenderableFolderWorkspaces } from '../../../../shared/sidebar-list/folder-workspace-lanes' import { worktreeMatchesVisibleHost } from '@/components/sidebar/worktree-list/listing/visible-worktree-host-scope' import { filterFolderWorkspacesFromOtherDevices, isWorkspaceOwnedBySomeoneElse -} from '../../../shared/workspace-creator-visibility' -import type { ExecutionHostId } from '../../../shared/execution-host' -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 { folderWorkspaceKey } from '../../../shared/workspace-scope' +} from '../../../../shared/workspace-creator-visibility' +import type { ExecutionHostId } from '../../../../shared/execution-host' +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 { folderWorkspaceKey } from '../../../../shared/workspace-scope' import type { StoredAgentAttentionUnread } from '@/attention/agent-attention-contract' -import type { TerminalTab } from '../../../shared/workspace-layout/terminal-tab-types' -import type { Tab } from '../../../shared/tab-types' -import type { Worktree } from '../../../shared/worktree/types' +import type { TerminalTab } from '../../../../shared/workspace-layout/terminal-tab-types' +import type { Tab } from '../../../../shared/tab-types' +import type { Worktree } from '../../../../shared/worktree/types' import { hasLiveTabMarker } from '@/store/slices/workspace-attention/workspace-live-markers' export type UnreadBadgeCountSources = { diff --git a/src/renderer/src/components/ClaudeAccountSwitchSessionTree.tsx b/src/renderer/src/components/ClaudeAccountSwitchSessionTree.tsx index 25ad85b58f6..c4be6ec382c 100644 --- a/src/renderer/src/components/ClaudeAccountSwitchSessionTree.tsx +++ b/src/renderer/src/components/ClaudeAccountSwitchSessionTree.tsx @@ -13,9 +13,9 @@ import { import { resolveWorktreeBranchLabel, resolveWorktreeDisplayName -} from '@/lib/worktree-default-display-name' +} from '@/lib/workspace/display/worktree-default-display-name' import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { useAppStore } from '../store' +import { useAppStore } from '../store/index' import { ResumeTreeRow } from './native-chat-recovery/tree/NativeChatResumeTreeRow' import { resumeSelectionState, diff --git a/src/renderer/src/components/LinearIssueWorkspace.tsx b/src/renderer/src/components/LinearIssueWorkspace.tsx index ba4bee4a91f..72623c4f848 100644 --- a/src/renderer/src/components/LinearIssueWorkspace.tsx +++ b/src/renderer/src/components/LinearIssueWorkspace.tsx @@ -5,9 +5,9 @@ import { LinearIssueTextEditor } from '@/components/LinearIssueTextEditor' import { Sheet, SheetContent, SheetDescription, SheetTitle } from '@/components/ui/sheet' import { findLinearIssueWorkspaceAttachment } from '@/lib/work-items/linear/linear-issue-workspace-attachment' import { openLinearIssueWorkspaceOrStart } from '@/lib/work-items/linear/linear-issue-workspace-open' -import { getWorktreeAttachmentLabel } from '@/lib/worktree-attachment-label' +import { getWorktreeAttachmentLabel } from '@/lib/workspace/display/worktree-attachment-label' import { folderWorkspaceToWorktree } from '../../../shared/folder-workspaces/folder-workspace-worktree' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { useAllWorktrees } from '@/store/slices/worktrees/listing/use-worktree-catalog' import type { LinearIssue } from '../../../shared/linear/issue-types' import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' diff --git a/src/renderer/src/components/LinearItemDrawer.tsx b/src/renderer/src/components/LinearItemDrawer.tsx index 30fecf6f88a..74eed4dece2 100644 --- a/src/renderer/src/components/LinearItemDrawer.tsx +++ b/src/renderer/src/components/LinearItemDrawer.tsx @@ -6,9 +6,9 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { findLinearIssueWorkspaceAttachment } from '@/lib/work-items/linear/linear-issue-workspace-attachment' import { openLinearIssueWorkspaceOrStart } from '@/lib/work-items/linear/linear-issue-workspace-open' -import { getWorktreeAttachmentLabel } from '@/lib/worktree-attachment-label' +import { getWorktreeAttachmentLabel } from '@/lib/workspace/display/worktree-attachment-label' import { folderWorkspaceToWorktree } from '../../../shared/folder-workspaces/folder-workspace-worktree' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { translate } from '@/i18n/i18n' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import { useAllWorktrees } from '@/store/slices/worktrees/listing/use-worktree-catalog' diff --git a/src/renderer/src/components/NotificationCardStack.tsx b/src/renderer/src/components/NotificationCardStack.tsx index f047c6d7662..c315855e263 100644 --- a/src/renderer/src/components/NotificationCardStack.tsx +++ b/src/renderer/src/components/NotificationCardStack.tsx @@ -2,11 +2,11 @@ import { useEffect, useRef, type ReactNode } from 'react' import { NOTIFICATION_CARD_STACK_BOTTOM, NOTIFICATION_CARD_STACK_HEIGHT_VAR -} from '@/lib/notification-card-stack-height' +} from '@/lib/notifications/notification-card-stack-height' import { registerNotificationCardLayoutVarReader, setNotificationCardLayoutVar -} from '@/lib/notification-card-layout-vars' +} from '@/lib/notifications/notification-card-layout-vars' const STACK_STYLE = { bottom: NOTIFICATION_CARD_STACK_BOTTOM, diff --git a/src/renderer/src/components/ZoomOverlay.tsx b/src/renderer/src/components/ZoomOverlay.tsx index 6a399b1bec0..66581de9e5e 100644 --- a/src/renderer/src/components/ZoomOverlay.tsx +++ b/src/renderer/src/components/ZoomOverlay.tsx @@ -1,7 +1,10 @@ import { useEffect, useRef, useState } from 'react' import { Search } from 'lucide-react' -import { ZOOM_LEVEL_CHANGED_EVENT } from '@/lib/zoom-events' -import type { ZoomLevelChangedEventDetail } from '@/lib/zoom-events' +import { + ZOOM_LEVEL_CHANGED_EVENT, + type ZoomLevelChangedEventDetail +} from '@/app-shell/chrome/zoom-events' + import { useTranslate } from '@/i18n/use-translate' // Unmount after fading so the fixed overlay cannot interfere with Radix layering, outside clicks or focus. diff --git a/src/renderer/src/components/activity/activity-thread-controls.tsx b/src/renderer/src/components/activity/activity-thread-controls.tsx index f90a355788e..bfc9c066c1c 100644 --- a/src/renderer/src/components/activity/activity-thread-controls.tsx +++ b/src/renderer/src/components/activity/activity-thread-controls.tsx @@ -4,7 +4,7 @@ import { AgentStateDot } from '@/components/AgentStateDot' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useNow } from '@/hooks/use-now' import { cn } from '@/lib/class-names' -import { formatShortTimeAgo } from '@/lib/short-time-ago' +import { formatShortTimeAgo } from '@/lib/time-format/short-time-ago' import { RepoBadgeMark } from '@/components/repo/RepoBadgeLabel' import type { Repo } from '../../../../shared/repo-types' import { diff --git a/src/renderer/src/components/activity/activity-thread-grouping.ts b/src/renderer/src/components/activity/activity-thread-grouping.ts index 1fcea62126c..28d73c3e415 100644 --- a/src/renderer/src/components/activity/activity-thread-grouping.ts +++ b/src/renderer/src/components/activity/activity-thread-grouping.ts @@ -3,7 +3,7 @@ import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import { formatAgentTypeLabel } from '../../../../shared/agent-status/presentation/agent-type-label' import { getAgentRowPrimaryText } from '../../../../shared/agent-status/presentation/agent-row-primary-text' -import { getActivityThreadWorkspaceTitle } from '@/lib/activity-thread-display' +import { getActivityThreadWorkspaceTitle } from '@/lib/workspace/activity/activity-thread-display' import { isClipboardTextByteLengthOverLimit } from '../../../../shared/clipboard-text' import { activityThreadStatusId, diff --git a/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx b/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx index 0d02ee03145..7119cfc97b0 100644 --- a/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx +++ b/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx @@ -30,7 +30,7 @@ import { } from '../sidebar/workspace-card/details/WorktreeCardDetailSection' import { EventTime, ThreadAgentStateIndicator } from './activity-thread-controls' import { activityThreadRowCopy, threadAgentStateLabel } from './activity-thread-presentation' -import { getActivityThreadWorkspaceTitle } from '@/lib/activity-thread-display' +import { getActivityThreadWorkspaceTitle } from '@/lib/workspace/activity/activity-thread-display' import type { AgentPaneThread } from './activity-thread-types' export function ActivityThreadHoverCardSummary({ diff --git a/src/renderer/src/components/activity/activity-thread-presentation.ts b/src/renderer/src/components/activity/activity-thread-presentation.ts index 92913fa6841..4811e4d244e 100644 --- a/src/renderer/src/components/activity/activity-thread-presentation.ts +++ b/src/renderer/src/components/activity/activity-thread-presentation.ts @@ -10,7 +10,7 @@ import { getActivityThreadTaskTitle, getActivityThreadWorkspaceTitle, resolveActivityThreadStatusPreview -} from '@/lib/activity-thread-display' +} from '@/lib/workspace/activity/activity-thread-display' import { formatUiRelativeTime } from '@/i18n/relative-time-format' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx b/src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx index aa9c0a5cf9a..10e58143629 100644 --- a/src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx +++ b/src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx @@ -1,6 +1,6 @@ -import { useMemo, type CSSProperties, type JSX, type ReactNode } from 'react' +import { useMemo } from 'react' +import type { CSSProperties, JSX, ReactNode } from 'react' import { ArrowUp, ChevronDown, Eye, Hand, Plus, X } from 'lucide-react' -import type { GlobalSettings } from '../../../../../shared/global-settings-types' import { FlowDiagram } from '@/components/feature-tips/ChatUiHereFeatureTipVisual' import { CHAT_DEMO_FILE, @@ -18,8 +18,9 @@ import { useSystemPrefersDark } from '@/hooks/theme/use-system-prefers-dark' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import { AgentIcon } from '@/components/agent/icons/AgentIcon' import { buildFontFamily } from '../../../../../shared/monospace-font-family' -import { resolveEffectiveTerminalAppearance } from '@/lib/terminal-theme' +import { resolveEffectiveTerminalAppearance } from '@/lib/terminal/appearance/terminal-theme' import { cn } from '@/lib/class-names' +import type { GlobalSettings } from '../../../../../shared/global-settings-types' // The tip's chat miniature, finished and denser so it fits a tile; nothing here animates. const CHAT_SCALE: CSSProperties & { '--chat-font-size': string } = { '--chat-font-size': '10px' } diff --git a/src/renderer/src/components/automations/authoring/AutomationProjectCombobox.tsx b/src/renderer/src/components/automations/authoring/AutomationProjectCombobox.tsx index 0c25f2bfcbe..9ca36679492 100644 --- a/src/renderer/src/components/automations/authoring/AutomationProjectCombobox.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationProjectCombobox.tsx @@ -7,7 +7,7 @@ import RepoBadgeLabel from '@/components/repo/RepoBadgeLabel' import { useAppStore } from '@/store/index' import { isGitRepoKind } from '../../../../../shared/repo-kind' import { getRepoExecutionHostId } from '../../../../../shared/execution-host' -import { isRepoSearchQueryTooLarge, searchRepos } from '@/lib/repo-search' +import { isRepoSearchQueryTooLarge, searchRepos } from '@/lib/workspace/catalog/repo-search' import { cn } from '@/lib/class-names' import { useMountedRef } from '@/hooks/useMountedRef' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/lib/automations-changed-window-event.ts b/src/renderer/src/components/automations/events/automations-changed-window-event.ts similarity index 91% rename from src/renderer/src/lib/automations-changed-window-event.ts rename to src/renderer/src/components/automations/events/automations-changed-window-event.ts index bb582287ebf..a0bdfaf94f5 100644 --- a/src/renderer/src/lib/automations-changed-window-event.ts +++ b/src/renderer/src/components/automations/events/automations-changed-window-event.ts @@ -1,5 +1,5 @@ /** Fan out authority changes within the renderer without coupling every publisher to the Automations page. */ -import type { AutomationsChangedPayload } from '../../../shared/runtime-client-events' +import type { AutomationsChangedPayload } from '../../../../../shared/runtime-client-events' export const AUTOMATIONS_CHANGED_EVENT = 'orca:automations-changed' diff --git a/src/renderer/src/components/automations/hosts/automation-host-invalidation-window-events.ts b/src/renderer/src/components/automations/hosts/automation-host-invalidation-window-events.ts index f56f380c2df..10c105787f7 100644 --- a/src/renderer/src/components/automations/hosts/automation-host-invalidation-window-events.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-invalidation-window-events.ts @@ -4,7 +4,7 @@ import { AUTOMATIONS_CHANGED_EVENT, automationsChangedWindowDetail, type AutomationsChangedWindowDetail -} from '@/lib/automations-changed-window-event' +} from '@/components/automations/events/automations-changed-window-event' import type { StableAutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' import type { AutomationAuthorityChangeEvent } from './automation-host-invalidation' diff --git a/src/renderer/src/components/automations/hosts/automation-target-availability.ts b/src/renderer/src/components/automations/hosts/automation-target-availability.ts index 9834d615ee7..1e04f05cdad 100644 --- a/src/renderer/src/components/automations/hosts/automation-target-availability.ts +++ b/src/renderer/src/components/automations/hosts/automation-target-availability.ts @@ -9,7 +9,7 @@ import { repoHostMatchesRunContext } from './automation-run-context-host-match' import { evaluateRuntimeCompat } from '../../../../../shared/protocol-compat' -import { describeRuntimeCompatBlock } from '@/lib/runtime-host-copy' +import { describeRuntimeCompatBlock } from '@/runtime/hosts/display/runtime-host-copy' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import { diff --git a/src/renderer/src/components/automations/hosts/use-automation-host-catalog.test.tsx b/src/renderer/src/components/automations/hosts/use-automation-host-catalog.test.tsx index 8cecc8d0d16..fc9acfc0d80 100644 --- a/src/renderer/src/components/automations/hosts/use-automation-host-catalog.test.tsx +++ b/src/renderer/src/components/automations/hosts/use-automation-host-catalog.test.tsx @@ -164,17 +164,6 @@ afterEach(async () => { document.body.innerHTML = '' }) -describe('useAutomationHostCatalog orphan bootstrap', () => { - it('projects the orphan entry a host answer reported', async () => { - desktopListScoped.mockResolvedValue({ automations: [], items: [], orphanCount: 2 }) - - await renderCatalog([]) - - // Committed orphan counts arrive only through cache changes; rederive the catalog without requiring a store write. - expect(view?.catalog.entries.map((entry) => entry.stableKey)).toContain('host:desktop:orphan') - }) -}) - describe('useAutomationHostCatalog on a paired web client', () => { const runtimeSelf = { authority: { kind: 'runtime', environmentId: ENVIRONMENT_ID }, diff --git a/src/renderer/src/components/automations/runs/automation-run-workspace-action.ts b/src/renderer/src/components/automations/runs/automation-run-workspace-action.ts index 82764baa8bd..7c6b8797c46 100644 --- a/src/renderer/src/components/automations/runs/automation-run-workspace-action.ts +++ b/src/renderer/src/components/automations/runs/automation-run-workspace-action.ts @@ -1,14 +1,12 @@ -import { openExistingStructuredSession } from '@/lib/open-existing-structured-session' +import { openExistingStructuredSession } from '@/lib/agent-session/open/open-existing-structured-session' import { ALL_TUI_AGENTS } from '../../../../../shared/agent-launch/catalog/tui-agent-display-names' import { isStructuredAgentSessionIdFor } from '../../../../../shared/agent-session/structured-agent-session-create' -import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import { activateAndRevealWorktree, activateAndRevealFolderWorkspace } from '@/lib/workspace/activation/worktree-activation' -import type { ActivateAndRevealResult } from '@/lib/workspace/activation/worktree-activation-outcome' import { activateWslMovedWorkspace } from '@/lib/workspace/activation/wsl-moved-chat-activation' import { useAppStore } from '@/store/index' import { activateTerminalTabOnOwner } from '@/lib/workspace/tabs/terminal-tab-owner-activation' @@ -17,6 +15,8 @@ import { resolveWebSessionVisibleTabId } from '@/runtime/web-session-tabs-sync/n import { parsePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' import { parseWorkspaceKey } from '../../../../../shared/workspace-scope' import { buildAutomationRunOpenLayout } from './automation-run-pane-layout' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' +import type { ActivateAndRevealResult } from '@/lib/workspace/activation/worktree-activation-outcome' import type { AutomationsPageActionContext } from '../automations-page-action-context' let cancelPendingReveal: (() => void) | undefined diff --git a/src/renderer/src/components/automations/use-automations-page-refresh.ts b/src/renderer/src/components/automations/use-automations-page-refresh.ts index 9a9742d8172..645c91dc6e8 100644 --- a/src/renderer/src/components/automations/use-automations-page-refresh.ts +++ b/src/renderer/src/components/automations/use-automations-page-refresh.ts @@ -1,7 +1,7 @@ import { useCallback, useEffect, useRef } from 'react' import { installWindowVisibilityInterval } from '@/lib/window-activity/window-visibility-interval' import { useAppStore } from '@/store/index' -import { AUTOMATIONS_CHANGED_EVENT } from '@/lib/automations-changed-window-event' +import { AUTOMATIONS_CHANGED_EVENT } from '@/components/automations/events/automations-changed-window-event' import { getAutomationHostTargetKey, getAutomationListedTargetFromHostId, diff --git a/src/renderer/src/components/browser-pane/agent-cursor/browser-agent-activity-state.ts b/src/renderer/src/components/browser-pane/agent-cursor/browser-agent-activity-state.ts index b9f95154d4f..98ce6117002 100644 --- a/src/renderer/src/components/browser-pane/agent-cursor/browser-agent-activity-state.ts +++ b/src/renderer/src/components/browser-pane/agent-cursor/browser-agent-activity-state.ts @@ -14,7 +14,9 @@ type BrowserAgentActivityMark = { pageId: string; revision: number } const activePageIds = new Set() /** The SSH host driving a page through the desktop browser bridge, by its label. */ const controllerHostByPage = new Map() -const lastActivityByWorktree = new Map() +/** Activity no chat claimed: older CLIs, remote hosts and terminal agents. */ +const lastUnclaimedActivityByWorktree = new Map() +const lastActivityByChatSession = new Map() const lastCursorByPage = new Map() const sinksByPage = new Map() const listeners = new Set<() => void>() @@ -37,7 +39,8 @@ export function setBrowserAgentPageActive( browserPageId: string, active: boolean, worktreeId: string | null, - controllerHostLabel?: string + controllerHostLabel?: string, + agentSessionId?: string ): void { if (active) { revision += 1 @@ -47,8 +50,11 @@ export function setBrowserAgentPageActive( } else { controllerHostByPage.delete(browserPageId) } - if (worktreeId) { - lastActivityByWorktree.set(worktreeId, { pageId: browserPageId, revision }) + const mark = { pageId: browserPageId, revision } + if (agentSessionId) { + lastActivityByChatSession.set(agentSessionId, mark) + } else if (worktreeId) { + lastUnclaimedActivityByWorktree.set(worktreeId, mark) } } else { activePageIds.delete(browserPageId) @@ -112,11 +118,15 @@ export function useBrowserAgentControllerHost( return useSyncExternalStore(subscribe, read, read) } -/** What an agent in this worktree drove most recently, while this window has been open. */ +/** What this chat's agent drove most recently; until it has claimed any, what an unclaimed agent in its worktree did. */ export function useLastBrowserAgentActivity( - worktreeId: string | null + worktreeId: string | null, + chatSessionId: string | null ): BrowserAgentActivityMark | null { + // A chat that claimed activity names itself on this host, so unclaimed activity is another agent's. const read = (): BrowserAgentActivityMark | null => - worktreeId ? (lastActivityByWorktree.get(worktreeId) ?? null) : null + (chatSessionId ? lastActivityByChatSession.get(chatSessionId) : undefined) ?? + (worktreeId ? lastUnclaimedActivityByWorktree.get(worktreeId) : undefined) ?? + null return useSyncExternalStore(subscribe, read, read) } diff --git a/src/renderer/src/components/browser-pane/annotate/use-browser-page-annotation-send.ts b/src/renderer/src/components/browser-pane/annotate/use-browser-page-annotation-send.ts index bb26b30562e..b986f14057d 100644 --- a/src/renderer/src/components/browser-pane/annotate/use-browser-page-annotation-send.ts +++ b/src/renderer/src/components/browser-pane/annotate/use-browser-page-annotation-send.ts @@ -1,17 +1,17 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { translate } from '@/i18n/i18n' import type { BrowserAnnotationIntent, BrowserPageAnnotation } from '../../../../../shared/browser/element-grab/browser-grab-types' -import { formatBrowserAnnotationsAsMarkdown } from './browser-annotation-output' +import { formatBrowserAnnotationsAsMarkdown } from '../../../../../shared/browser/annotations/browser-annotation-output' import { EMPTY_BROWSER_ANNOTATIONS } from '../describe-page/browser-annotation-geometry' import { holdNotesForSend, isNoteInFlight, useNotesInFlightVersion -} from '@/lib/notes-send-in-flight' +} from '@/components/notes/delivery/notes-send-in-flight' import { recomputeOn } from '@/lib/recompute-on' export function useBrowserPageAnnotationSend({ diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-link-status-bubble.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-link-status-bubble.tsx index 8b3c067ddcf..496f05fb914 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-link-status-bubble.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-link-status-bubble.tsx @@ -1,6 +1,6 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { cn } from '@/lib/class-names' -import { windowDipToCssPx } from '@/lib/ui-zoom' +import { windowDipToCssPx } from '@/app-shell/chrome/ui-zoom' import { toDisplayUrl } from '../describe-page/browser-page-url-display' // Chrome's status bubble timings (status_bubble_views.cc, status_bubble.h). diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-context-menu.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-context-menu.tsx index 076f6934cb1..2d8520157cb 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-context-menu.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-context-menu.tsx @@ -1,4 +1,4 @@ -import { windowDipToCssPx } from '@/lib/ui-zoom' +import { windowDipToCssPx } from '@/app-shell/chrome/ui-zoom' import { useCallback, useEffect, diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-page-window-close.test.ts b/src/renderer/src/components/browser-pane/host-guest/browser-page-window-close.test.ts index 257250b024a..7f10e7912b4 100644 --- a/src/renderer/src/components/browser-pane/host-guest/browser-page-window-close.test.ts +++ b/src/renderer/src/components/browser-pane/host-guest/browser-page-window-close.test.ts @@ -12,9 +12,15 @@ vi.mock('@/lib/workspace/tabs/workspace-tab-commands', () => ({ import { handleGuestWindowCloseMessage } from './browser-page-window-close' import { BROWSER_GUEST_WINDOW_CLOSE_CHANNEL } from '../../../../../shared/browser-guest-window-close' -function seedTab(pageId: string, isPinned = false, siblingPageIds: string[] = []): void { +function seedTab( + pageId: string, + isPinned = false, + siblingPageIds: string[] = [], + browserAnnotationsByPageId: Record = {} +): void { storeState.value = { closeBrowserPage: closeBrowserPageMock, + browserAnnotationsByPageId, browserTabsByWorktree: { 'wt-1': [{ id: 'ws-1' }] }, browserPagesByWorkspace: { 'ws-1': [{ id: pageId }, ...siblingPageIds.map((id) => ({ id }))] }, unifiedTabsByWorktree: { @@ -40,6 +46,13 @@ describe('window.close() from a browser page', () => { expect(dispatchMock).not.toHaveBeenCalled() }) + it('never discards unsent notes', () => { + seedTab('page-n', false, [], { 'page-n': [{ id: 'note-1' }] }) + closeFrom('page-n', { back: false, forward: false }) + expect(dispatchMock).not.toHaveBeenCalled() + expect(closeBrowserPageMock).not.toHaveBeenCalled() + }) + it('closes only the calling page when its Orca tab holds other pages', () => { seedTab('page-e', false, ['page-sibling']) closeFrom('page-e', { back: false, forward: false }) diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-page-window-close.ts b/src/renderer/src/components/browser-pane/host-guest/browser-page-window-close.ts index 452f602c2b1..5b37f60164e 100644 --- a/src/renderer/src/components/browser-pane/host-guest/browser-page-window-close.ts +++ b/src/renderer/src/components/browser-pane/host-guest/browser-page-window-close.ts @@ -32,7 +32,8 @@ export function handleGuestWindowCloseMessage( const tab = (state.unifiedTabsByWorktree[owner.worktreeId] ?? []).find( (candidate) => candidate.contentType === 'browser' && candidate.entityId === owner.workspaceId ) - if (tab?.isPinned) { + // A script may not discard what the user pinned or left unsent; the page's notes are all it closes. + if (tab?.isPinned || (state.browserAnnotationsByPageId[pageId]?.length ?? 0) > 0) { return } pagesOpenedByPage.delete(pageId) diff --git a/src/renderer/src/components/browser-pane/host-guest/use-browser-page-viewport-size-feedback.ts b/src/renderer/src/components/browser-pane/host-guest/use-browser-page-viewport-size-feedback.ts index 994739f8939..0b74128b956 100644 --- a/src/renderer/src/components/browser-pane/host-guest/use-browser-page-viewport-size-feedback.ts +++ b/src/renderer/src/components/browser-pane/host-guest/use-browser-page-viewport-size-feedback.ts @@ -1,5 +1,5 @@ import { useEffect } from 'react' -import { getUIZoomFactor } from '@/lib/ui-zoom' +import { getUIZoomFactor } from '@/app-shell/chrome/ui-zoom' import { browserPageZoomLevelToFactor } from '../../../../../shared/browser-page-zoom' export type BrowserPageViewportSize = { width: number; height: number } diff --git a/src/renderer/src/components/browser-pane/new-tab/BrowserNewTabPage.tsx b/src/renderer/src/components/browser-pane/new-tab/BrowserNewTabPage.tsx index 64c6e8d8715..ba86e920306 100644 --- a/src/renderer/src/components/browser-pane/new-tab/BrowserNewTabPage.tsx +++ b/src/renderer/src/components/browser-pane/new-tab/BrowserNewTabPage.tsx @@ -2,7 +2,7 @@ import { useMemo } from 'react' import { Globe } from 'lucide-react' import { toast } from 'sonner' import { useTranslate } from '@/i18n/use-translate' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { useRepoById } from '@/store/repos/use-repository-catalog' import { useWorktreeById } from '@/store/workspaces/selection/use-selected-worktree' import { @@ -19,7 +19,7 @@ import { useBrowserNewTabLinkedItems } from './use-browser-new-tab-linked-items' import { useBrowserNewTabServers, type BrowserNewTabServers } from './use-browser-new-tab-servers' import { BrowserNewTabWorkspaceCard } from './browser-new-tab-workspace-card' import { BrowserImportHintButton } from '../assemble-chrome/BrowserImportHintButton' -import { resolveWorktreeDisplayName } from '@/lib/worktree-default-display-name' +import { resolveWorktreeDisplayName } from '@/lib/workspace/display/worktree-default-display-name' import { useWorktreeRuntimeTarget } from '@/runtime/rpc/targets/use-worktree-runtime-target' import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' diff --git a/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-document-actions.test.ts b/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-document-actions.test.ts deleted file mode 100644 index bf39fa73149..00000000000 --- a/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-document-actions.test.ts +++ /dev/null @@ -1,163 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => ({ - /** What the per-file resolver answers: null local, a string remote, undefined unresolved. */ - connectionIdForFile: null as string | null | undefined, - /** What the workspace-scoped resolver answers, which is not always the same thing. */ - connectionIdForWorkspace: null as string | null | undefined, - worktreePath: '/srv/repo' as string | null, - /** What the worktree resolves its runtime owner to, which the grant was minted against. */ - worktreeRuntimeOwnerId: null as string | null, - activeRuntimeEnvironmentId: undefined as string | undefined, - twin: false, - openFile: vi.fn(), - openFilePath: vi.fn().mockResolvedValue(true), - downloadAndOpen: vi.fn(), - toastError: vi.fn() -})) - -vi.mock('sonner', () => ({ toast: { error: mocks.toastError } })) -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string, params?: Record) => - fallback.replace('{{value0}}', params?.value0 ?? '') -})) - -vi.mock('@/lib/workspace/ownership/connection-owner-resolution', () => ({ - getConnectionIdForFileFromState: () => mocks.connectionIdForFile -})) -vi.mock('@/lib/workspace/ownership/worktree-runtime-owner', () => ({ - runtimeEnvironmentIdOrLocalUnlessTwin: () => mocks.worktreeRuntimeOwnerId -})) -vi.mock('@/lib/files/access/file-owner-runtime-target', () => { - const getRuntimeTargetForFileOwner = ( - _state: unknown, - _worktreeId: string | null | undefined, - runtimeEnvironmentId: string | null | undefined - ) => { - const owner = - runtimeEnvironmentId === undefined ? mocks.worktreeRuntimeOwnerId : runtimeEnvironmentId - return owner - ? { kind: 'environment' as const, environmentId: owner } - : { kind: 'local' as const } - } - return { - FILE_OWNER_UNRESOLVED_MESSAGE: 'unresolved', - getRuntimeTargetForFileOwner, - requireRuntimeTargetForFileOwner: getRuntimeTargetForFileOwner, - getRuntimeTargetForWorktreeOwner: (state: unknown, worktreeId: string | null | undefined) => - getRuntimeTargetForFileOwner(state, worktreeId, undefined) - } -}) -vi.mock('@/lib/workspace/ownership/connection-context', () => ({ - getConnectionId: () => mocks.connectionIdForWorkspace, - getConnectionIdForFile: () => mocks.connectionIdForFile -})) -vi.mock('@/components/terminal-pane/links/files/terminal-remote-file-download-open', () => ({ - downloadAndOpenRemoteTerminalFile: mocks.downloadAndOpen -})) -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => ({ - settings: { - activeRuntimeEnvironmentId: mocks.activeRuntimeEnvironmentId - }, - getKnownWorktreeById: () => - mocks.worktreePath === null ? undefined : { id: 'wt-1', path: mocks.worktreePath }, - ...(mocks.twin ? localAndSshTwinRows('repo', 'repo::/srv/repo') : {}), - openFile: mocks.openFile - }) - } -})) -import { openDocPreviewExternally } from './doc-preview-document-actions' -import { localAndSshTwinRows } from '@/lib/workspace-twin-rows.test-fixture' - -const REMOTE_DOCUMENT = { - filePath: '/root/demo/report/index.html', - relativePath: 'report/index.html', - worktreeId: 'wt-1', - runtimeEnvironmentId: null, - externalSshTargetId: null -} - -beforeEach(() => { - vi.clearAllMocks() - mocks.connectionIdForFile = null - mocks.connectionIdForWorkspace = null - mocks.worktreePath = '/srv/repo' - mocks.worktreeRuntimeOwnerId = null - mocks.activeRuntimeEnvironmentId = undefined - mocks.twin = false - mocks.openFilePath.mockResolvedValue(true) - vi.stubGlobal('window', { api: { shell: { openFilePath: mocks.openFilePath } } }) -}) - -describe('openDocPreviewExternally', () => { - // Folder workspaces may span hosts; unresolved workspace ownership must not override a resolved file owner. - it('routes on the file owner when the workspace-scoped owner is unresolved', () => { - mocks.connectionIdForFile = 'ssh-1' - mocks.connectionIdForWorkspace = undefined - - openDocPreviewExternally(REMOTE_DOCUMENT) - - expect(mocks.openFilePath).not.toHaveBeenCalled() - expect(mocks.downloadAndOpen).toHaveBeenCalledWith( - expect.objectContaining({ connectionId: 'ssh-1' }), - REMOTE_DOCUMENT.filePath - ) - }) - - // Unknown ownership must refuse: downloading could otherwise read an unrelated same-named local file. - it("refuses a document of a project two hosts publish instead of opening this machine's copy", () => { - mocks.twin = true - - openDocPreviewExternally({ ...REMOTE_DOCUMENT, worktreeId: 'repo::/srv/repo' }) - - expect(mocks.openFilePath).not.toHaveBeenCalled() - expect(mocks.toastError).toHaveBeenCalled() - }) - - it('refuses instead of reading this machine when no owner resolves', () => { - mocks.connectionIdForFile = undefined - mocks.connectionIdForWorkspace = undefined - - openDocPreviewExternally(REMOTE_DOCUMENT) - - expect(mocks.openFilePath).not.toHaveBeenCalled() - expect(mocks.downloadAndOpen).not.toHaveBeenCalled() - expect(mocks.toastError).toHaveBeenCalledWith(expect.stringContaining('report/index.html')) - }) - - // Vary only the root so other remote-owner fields cannot mask this independent OS-open guard. - it('refuses a document whose workspace root is unknown even when nothing names another host', () => { - mocks.worktreePath = null - - openDocPreviewExternally(REMOTE_DOCUMENT) - - expect(mocks.openFilePath).not.toHaveBeenCalled() - expect(mocks.downloadAndOpen).not.toHaveBeenCalled() - expect(mocks.toastError).toHaveBeenCalled() - }) - - // A torn-down runtime may leave only the tab’s recorded owner. - it('falls back to the tab runtime owner when the worktree resolves none', () => { - mocks.worktreeRuntimeOwnerId = null - mocks.activeRuntimeEnvironmentId = 'env-9' - - openDocPreviewExternally({ ...REMOTE_DOCUMENT, runtimeEnvironmentId: 'env-9' }) - - expect(mocks.openFilePath).not.toHaveBeenCalled() - expect(mocks.toastError).not.toHaveBeenCalled() - expect(mocks.downloadAndOpen).toHaveBeenCalled() - }) - - // Restored tabs can lack the owner used to mint their grant; consult the resolved worktree owner before choosing OS-open. - it('routes on the worktree runtime owner when the tab carries none', () => { - mocks.worktreeRuntimeOwnerId = 'env-1' - mocks.activeRuntimeEnvironmentId = 'env-1' - - openDocPreviewExternally({ ...REMOTE_DOCUMENT, runtimeEnvironmentId: null }) - - expect(mocks.openFilePath).not.toHaveBeenCalled() - expect(mocks.downloadAndOpen).toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/cmd-j/palette-live-status.tsx b/src/renderer/src/components/cmd-j/palette-live-status.tsx index bebe0cfe96f..bb3d6f395db 100644 --- a/src/renderer/src/components/cmd-j/palette-live-status.tsx +++ b/src/renderer/src/components/cmd-j/palette-live-status.tsx @@ -1,6 +1,6 @@ import React, { createContext, useContext, useMemo } from 'react' import { useShallow } from 'zustand/react/shallow' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { hasAwakeStructuredChat } from '@/store/slices/agent-status/structured-chat-slept-at' import { AgentStateDot } from '@/components/AgentStateDot' import { StateIndicatorTooltip } from '@/components/StateIndicatorTooltip' @@ -15,19 +15,14 @@ import { isAgentStatusFresh, AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status/contracts/agent-status-freshness' -import { - getLiveAgentStatusByWorktreeId, - type LiveAgentWorktreeStatus -} from '@/lib/worktree-activity-state' -import { - getWorktreeStatus, - getWorktreeStatusLabel, - type WorktreeStatus -} from '@/lib/worktree-status' +import { getLiveAgentStatusByWorktreeId } from '@/lib/workspace/activity/worktree-activity-state' +import type { LiveAgentWorktreeStatus } from '../../../../shared/sidebar-list/workspace-activity-facts' +import { getWorktreeStatus, getWorktreeStatusLabel } from '@/lib/workspace/activity/worktree-status' +import type { WorktreeStatus } from '../../../../shared/worktree-status-rollup' import { resolveRecentWorkspaceTabStatus, type RecentWorkspaceTabRow -} from '@/lib/recent-workspace-tab-rows' +} from '@/lib/workspace/search/palette/recent-workspace-tab-rows' import { resolveTerminalTabAttentionBadge, terminalTabHasUnreadActivity, diff --git a/src/renderer/src/components/cmd-j/plugin-quick-actions.ts b/src/renderer/src/components/cmd-j/plugin-quick-actions.ts index a9137f7ed83..7ae53f78be7 100644 --- a/src/renderer/src/components/cmd-j/plugin-quick-actions.ts +++ b/src/renderer/src/components/cmd-j/plugin-quick-actions.ts @@ -1,11 +1,11 @@ import { Blocks, FilePlus } from 'lucide-react' import { isWorkspaceScopedPluginContext } from '../../../../shared/plugins/contributions/plugin-command-contribution' import type { ActivePluginCommand } from '@/store/plugins/catalog/plugin-contribution-catalog' -import { executePluginCommand } from '@/lib/plugin-command-execution' +import { executePluginCommand } from '@/lib/plugins/commands/plugin-command-execution' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import type { ActivePluginNewFile } from '@/store/plugins/file-creation/plugin-new-files' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { runWorkspaceAction, type CmdJQuickAction } from './quick-actions' import { getWorkspaceScopedActionAvailability } from './quick-action-context' diff --git a/src/renderer/src/components/cmd-j/quick-action-context.ts b/src/renderer/src/components/cmd-j/quick-action-context.ts index 62cea06a987..a69d82df00e 100644 --- a/src/renderer/src/components/cmd-j/quick-action-context.ts +++ b/src/renderer/src/components/cmd-j/quick-action-context.ts @@ -1,16 +1,16 @@ -import type { AppState } from '@/store/types' import { translate } from '@/i18n/i18n' import { findFirstIndexedWorktree } from '@/lib/workspace/ownership/worktree-runtime-owner-index' -import type { Worktree } from '../../../../shared/worktree/types' -import type { SshConnectionStatus } from '../../../../shared/ssh-types' -import { getClientCreationActionPolicy } from '@/lib/client-creation-action-policy' +import { getClientCreationActionPolicy } from '@/lib/workspace/creation/surface-policy/client-creation-action-policy' import { canRunNativeChatSplitTarget, resolveActiveNativeChatSplitTarget, runActiveNativeChatSplit } from '@/components/native-chat/pane/routing/native-chat-layout-actions' -import type { NativeChatSplitDirection } from '@/components/native-chat/pane/routing/native-chat-pane-shortcut' import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' +import type { AppState } from '@/store/types' +import type { Worktree } from '../../../../shared/worktree/types' +import type { SshConnectionStatus } from '../../../../shared/ssh-types' +import type { NativeChatSplitDirection } from '@/components/native-chat/pane/routing/native-chat-pane-shortcut' import type { TabSplitDirection } from '@/store/slices/tabs/tabs-slice-contract' export type CmdJUnavailableReason = diff --git a/src/renderer/src/components/cmd-j/worktree-checks-review-index.ts b/src/renderer/src/components/cmd-j/worktree-checks-review-index.ts index bb2fb2af3bf..84cd07fe5f8 100644 --- a/src/renderer/src/components/cmd-j/worktree-checks-review-index.ts +++ b/src/renderer/src/components/cmd-j/worktree-checks-review-index.ts @@ -1,4 +1,4 @@ -import { resolveWorktreeBranchLabel } from '@/lib/worktree-default-display-name' +import { resolveWorktreeBranchLabel } from '@/lib/workspace/display/worktree-default-display-name' import { resolvePaletteRepoForWorktree } from '@/lib/workspace/search/palette-repo-resolution' import { getGitHubPRCacheKey } from '../../../../shared/github/github-cache-key' import { getHostedReviewCacheKey } from '@/store/slices/hosted-review/hosted-review-cache-identity' diff --git a/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx b/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx index f5ced3a45ee..952a64d9b1f 100644 --- a/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx +++ b/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx @@ -1,6 +1,4 @@ -import type { PreviewTerminalLinkHandler } from './preview-terminal-links' import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' -import type { ITheme, Terminal } from '@xterm/xterm' import { useShallow } from 'zustand/react/shallow' import { composeActiveTerminalTheme } from '@/components/terminal-pane/appearance/terminal-appearance' import { useSystemPrefersDark } from '@/hooks/theme/use-system-prefers-dark' @@ -13,29 +11,26 @@ import { previewAdvertisesKittyKeyboard } from './preview-terminal-options' import { syncPreviewTerminalLigatures } from './preview-terminal-ligatures' -import type { DashboardCardTerminalInput } from '../../../../shared/dashboard-snapshot' import { terminalPreviewUnavailableMessage } from './terminal-preview-unavailable-message' -import { resolveEffectiveTerminalAppearance } from '@/lib/terminal-theme' +import { resolveEffectiveTerminalAppearance } from '@/lib/terminal/appearance/terminal-theme' import { cn } from '@/lib/class-names' import { useAppStore } from '@/store/index' import { usePluginFontReady } from '@/store/plugins/appearance/plugin-fonts' import { createPreviewGridClaim } from './preview-grid-claim' import { createPreviewBoxFit } from './preview-terminal-box-fit' -import { - openStandaloneTerminal, - type StandaloneTerminal -} from '../standalone-terminal/open-standalone-terminal' -import type { TerminalPreviewDataPayload } from '../../../../shared/terminal/replay/terminal-preview' +import { openStandaloneTerminal } from '../standalone-terminal/open-standalone-terminal' +import type { StandaloneTerminal } from '../standalone-terminal/open-standalone-terminal' import { terminalPreviewApiFor } from './terminal-preview-api' - import { LinkActionPopover } from '@/components/link-actions/LinkActionPopover' -import { - closeLinkActionRequest, - type LinkActionRequest -} from '@/components/link-actions/link-action-request' +import { closeLinkActionRequest } from '@/components/link-actions/link-action-request' +import type { LinkActionRequest } from '@/components/link-actions/link-action-request' import { installDashboardPreviewLinkInteraction } from './dashboard-preview-link-interaction' -import type { DashboardPreviewLinkSource } from './dashboard-preview-http-actions' import { useTranslate } from '@/i18n/use-translate' +import type { PreviewTerminalLinkHandler } from './preview-terminal-links' +import type { ITheme, Terminal } from '@xterm/xterm' +import type { DashboardCardTerminalInput } from '../../../../shared/dashboard-snapshot' +import type { TerminalPreviewDataPayload } from '../../../../shared/terminal/replay/terminal-preview' +import type { DashboardPreviewLinkSource } from './dashboard-preview-http-actions' const PREVIEW_SCROLLBACK_ROWS = 24 // Preview snapshots bound history; pane scrollback would only cost memory. diff --git a/src/renderer/src/components/dashboard-popout/dashboard-preview-http-actions.ts b/src/renderer/src/components/dashboard-popout/dashboard-preview-http-actions.ts index d2bf0a8f9b3..91bd1aef3a0 100644 --- a/src/renderer/src/components/dashboard-popout/dashboard-preview-http-actions.ts +++ b/src/renderer/src/components/dashboard-popout/dashboard-preview-http-actions.ts @@ -1,29 +1,31 @@ import { toast } from 'sonner' import { intentPresentation } from '@/lib/browser/workspace/workspace-browser-tab-presentation' -import type { DashboardCard } from '../../../../shared/dashboard-snapshot' import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id' import { parseRoutableExecutionHostId } from '../../../../shared/execution-host' import { parseRemoteRuntimePtyId, isRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { resolveOwner } from '@/lib/workspace/ownership/resolve-owner' import { resolveWorktreeOperationRoute } from '@/lib/workspace/ownership/worktree-operation-route' import { createBrowserLinkHostMatcher } from '@/lib/browser/navigation/browser-link-owner' -import { getWorkspaceClientCreationActionPolicy } from '@/lib/client-creation-action-policy' +import { getWorkspaceClientCreationActionPolicy } from '@/lib/workspace/creation/surface-policy/client-creation-action-policy' import { canOpenWorkspaceBrowserTabOnRuntime, canOpenWorkspaceBrowserTabOnSsh } from '@/lib/browser/workspace/workspace-browser-route-eligibility' -import type { HttpLinkSourceOwner } from '@/lib/browser/navigation/http-link-routing' import { buildHttpLinkActions, httpLinkActionDestinationsFor, - openRoutedHttpLink, - type HttpLinkDestination, - type HttpLinkActionDestinations + openRoutedHttpLink } from '@/lib/browser/navigation/http-link-destinations' +import type { + HttpLinkDestination, + HttpLinkActionDestinations +} from '@/lib/browser/navigation/http-link-destinations' +import type { DashboardCard } from '../../../../shared/dashboard-snapshot' +import type { HttpLinkSourceOwner } from '@/lib/browser/navigation/http-link-routing' export type DashboardPreviewLinkSource = Pick< DashboardCard, diff --git a/src/renderer/src/components/dashboard/agent-dashboard-open-mode.ts b/src/renderer/src/components/dashboard/agent-dashboard-open-mode.ts index 69606c87259..1e570af3cd7 100644 --- a/src/renderer/src/components/dashboard/agent-dashboard-open-mode.ts +++ b/src/renderer/src/components/dashboard/agent-dashboard-open-mode.ts @@ -1,6 +1,6 @@ import type { GlobalSettings } from '../../../../shared/global-settings-types' import type { AgentDashboardMode } from '../../../../shared/ui-chrome-types' -import { isPairedWebClientWindow } from '@/lib/desktop-window-chrome' +import { isPairedWebClientWindow } from '@/app-shell/chrome/desktop-window-chrome' /** A browser tab cannot open a second Orca window, so a web client only has the in-window board. */ export function canOpenAgentDashboardPopout(): boolean { diff --git a/src/renderer/src/components/dashboard/dashboard-card-labels.ts b/src/renderer/src/components/dashboard/dashboard-card-labels.ts index 3440cad19e5..ce2310922be 100644 --- a/src/renderer/src/components/dashboard/dashboard-card-labels.ts +++ b/src/renderer/src/components/dashboard/dashboard-card-labels.ts @@ -1,15 +1,13 @@ import { getAgentRowConversationName } from '../../../../shared/agent-status/presentation/agent-row-conversation-name' import { DASHBOARD_MAX_LABEL_LENGTH } from '../../../../shared/dashboard-snapshot' import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' -import type { TerminalLayoutSnapshot } from '../../../../shared/workspace-layout/terminal-tab-types' import { resolveAgentRowPaneLiveTitle } from './agent-row-pane-live-title' +import { structuredChatTabById } from '@/lib/agent-session/tab-identity/structured-chat-tab-index' +import { projectedStructuredChatTabName } from '@/runtime/native-chat/naming/structured-chat-tab-name' +import type { StructuredChatTabNames } from '@/runtime/native-chat/naming/structured-chat-tab-name' +import type { TerminalLayoutSnapshot } from '../../../../shared/workspace-layout/terminal-tab-types' import type { DashboardAgentRow } from './useDashboardData' import type { AppState } from '@/store/types' -import { structuredChatTabById } from '@/lib/structured-chat-tab-index' -import { - projectedStructuredChatTabName, - type StructuredChatTabNames -} from '@/runtime/native-chat/naming/structured-chat-tab-name' export function rowTask(row: DashboardAgentRow): string { return (row.entry.orchestration?.taskTitle ?? '').trim() || (row.entry.prompt ?? '').trim() diff --git a/src/renderer/src/components/dashboard/use-agent-row-conversation-name.ts b/src/renderer/src/components/dashboard/use-agent-row-conversation-name.ts index add52e79690..1fa9c15b620 100644 --- a/src/renderer/src/components/dashboard/use-agent-row-conversation-name.ts +++ b/src/renderer/src/components/dashboard/use-agent-row-conversation-name.ts @@ -3,7 +3,7 @@ import { getAgentRowConversationName } from '../../../../shared/agent-status/pre import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { structuredChatDisplayName } from '../../../../shared/structured-chat-row-name' import { resolveAgentRowPaneLiveTitle } from './agent-row-pane-live-title' -import { structuredChatTabById } from '@/lib/structured-chat-tab-index' +import { structuredChatTabById } from '@/lib/agent-session/tab-identity/structured-chat-tab-index' import { useStructuredChatTabConversationName } from '@/runtime/native-chat/naming/structured-conversation-name' import type { AppState } from '@/store/types' import type { DashboardAgentRow } from './useDashboardData' diff --git a/src/renderer/src/components/dictation/speech-model-update-check.ts b/src/renderer/src/components/dictation/speech-model-update-check.ts index b781c271abd..ff2c433db48 100644 --- a/src/renderer/src/components/dictation/speech-model-update-check.ts +++ b/src/renderer/src/components/dictation/speech-model-update-check.ts @@ -1,5 +1,5 @@ -import { useAppStore } from '@/store' -import { isPairedWebClientWindow } from '@/lib/desktop-window-chrome' +import { useAppStore } from '@/store/index' +import { isPairedWebClientWindow } from '@/app-shell/chrome/desktop-window-chrome' import type { SpeechModelManifest, VoiceSettings } from '../../../../shared/speech-types' import { findSpeechModelUpdateTarget, diff --git a/src/renderer/src/components/dictation/use-hold-dictation-gesture.ts b/src/renderer/src/components/dictation/use-hold-dictation-gesture.ts index 2f47c5aa009..e6a31dc01fa 100644 --- a/src/renderer/src/components/dictation/use-hold-dictation-gesture.ts +++ b/src/renderer/src/components/dictation/use-hold-dictation-gesture.ts @@ -9,7 +9,7 @@ import { textInputOwnsComposition } from '../../../../shared/text-input-shortcut import type { GlobalSettings } from '../../../../shared/global-settings-types' import { dictationShortcutMode } from '../../../../shared/dictation-shortcut-mode' import { addAppKeyListener, removeAppKeyListener } from '@/lib/keyboard/app-keyboard-router' -import { showTerminalShortcutCaptureNotification } from '@/lib/terminal-shortcut-capture-notification' +import { showTerminalShortcutCaptureNotification } from '@/lib/notifications/terminal-shortcut-capture-notification' import { getKeybindingContext } from '../terminal-workspace-model' type HoldDictationGestureOptions = { diff --git a/src/renderer/src/components/editor/EditorPanelHeaderPath.test.tsx b/src/renderer/src/components/editor/EditorPanelHeaderPath.test.tsx deleted file mode 100644 index 20d14859278..00000000000 --- a/src/renderer/src/components/editor/EditorPanelHeaderPath.test.tsx +++ /dev/null @@ -1,138 +0,0 @@ -// @vitest-environment happy-dom - -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import type * as I18nModule from '@/i18n/i18n' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { EditorPanelHeaderPath } from './EditorPanelHeaderPath' - -const renameFileOnDiskMock = vi.hoisted(() => vi.fn()) - -vi.mock('@/store/workspaces/selection/use-selected-worktree', () => ({ - useWorktreeById: () => ({ path: '/repo', repoId: 'repo-1' }) -})) - -// Stub owner resolution because this suite does not seed the execution-host catalog. -vi.mock('@/lib/resolved-worktree-execution-host', () => ({ - getResolvedExecutionHostIdForWorktree: () => 'local' -})) - -vi.mock('@/lib/editor/file-operations/rename-file', () => ({ - renameFileOnDisk: renameFileOnDiskMock -})) - -vi.mock('@/hooks/useShortcutLabel', () => ({ - useShortcutLabel: () => '' -})) - -vi.mock('@/i18n/i18n', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - translate: (_key: string, fallback: string, options?: { value0?: string }) => - fallback.replace('{{value0}}', options?.value0 ?? '') - } -}) - -afterEach(cleanup) - -function baseFile(overrides: Partial = {}): OpenFile { - return { - id: '/repo/notes.md', - filePath: '/repo/notes.md', - relativePath: 'notes.md', - worktreeId: 'wt-1', - language: 'markdown', - isDirty: false, - mode: 'edit', - ...overrides - } -} - -function renderPath(file: OpenFile): (next: OpenFile) => void { - const view = render( - - ) - return (next) => - view.rerender( - - ) -} - -function getRenameInput(label: string): HTMLInputElement { - const input = screen.getByLabelText(label) - if (!(input instanceof HTMLInputElement)) { - throw new Error(`Missing rename input: ${label}`) - } - return input -} - -function openRenameInput(): void { - const pathRow = document.querySelector('.editor-header-path-row') - if (!pathRow) { - throw new Error('Missing editor header path row') - } - fireEvent.contextMenu(pathRow) - fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' })) -} - -describe('EditorPanelHeaderPath inline rename', () => { - beforeEach(() => { - renameFileOnDiskMock.mockReset() - Object.assign(window, { api: { ui: { writeClipboardText: vi.fn() } } }) - vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { - callback(0) - return 1 - }) - vi.stubGlobal('cancelAnimationFrame', vi.fn()) - }) - - it('cancels on Escape without a trailing blur-commit, and ignores empty renames', () => { - renderPath(baseFile()) - openRenameInput() - - const input = getRenameInput('Rename file notes.md') - fireEvent.change(input, { target: { value: 'renamed.md' } }) - fireEvent.keyDown(input, { key: 'Escape' }) - fireEvent.blur(input) - expect(renameFileOnDiskMock).not.toHaveBeenCalled() - expect(screen.queryByLabelText('Rename file notes.md')).toBeNull() - - openRenameInput() - fireEvent.change(getRenameInput('Rename file notes.md'), { target: { value: ' ' } }) - fireEvent.keyDown(getRenameInput('Rename file notes.md'), { key: 'Enter' }) - expect(renameFileOnDiskMock).not.toHaveBeenCalled() - }) - - it('drops rename mode when the active file changes', () => { - const rerenderPath = renderPath(baseFile()) - openRenameInput() - - const input = getRenameInput('Rename file notes.md') - fireEvent.change(input, { target: { value: 'renamed.md' } }) - rerenderPath( - baseFile({ - id: '/repo/other.md', - filePath: '/repo/other.md', - relativePath: 'other.md' - }) - ) - - expect(screen.queryByLabelText('Rename file notes.md')).toBeNull() - expect(screen.queryByLabelText('Rename file other.md')).toBeNull() - - expect(renameFileOnDiskMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/editor/autosave/editor-autosave.ts b/src/renderer/src/components/editor/autosave/editor-autosave.ts index e7219b0d8eb..0d09179ff5d 100644 --- a/src/renderer/src/components/editor/autosave/editor-autosave.ts +++ b/src/renderer/src/components/editor/autosave/editor-autosave.ts @@ -1,15 +1,15 @@ import { joinPath } from '@/lib/path' -import type { OpenFile } from '@/store/slices/editor/types/open-file' import { areLocalWindowsWslPathAliases } from '../../../../../shared/cross-platform-path' import { externalChangePathKeyFor } from '@/store/slices/editor/buffers/editor-buffer-identity' -import { isLocalWindowsDesktopClient } from '@/lib/desktop-window-chrome' +import { isLocalWindowsDesktopClient } from '@/app-shell/chrome/desktop-window-chrome' import { DEFAULT_EDITOR_AUTO_SAVE_DELAY_MS, MAX_EDITOR_AUTO_SAVE_DELAY_MS, MIN_EDITOR_AUTO_SAVE_DELAY_MS } from '../../../../../shared/constants' -import { clampNumber } from '@/lib/terminal-theme' +import { clampNumber } from '@/lib/terminal/appearance/terminal-theme' import { isAutosavePausedForNonUtf8File } from './editor-non-utf8-autosave-pause' +import type { OpenFile } from '@/store/slices/editor/types/open-file' export const ORCA_EDITOR_QUIESCE_FILE_SAVES_EVENT = 'orca:editor-quiesce-file-saves' export const ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT = 'orca:editor-external-file-change' diff --git a/src/renderer/src/components/editor/editor-dropped-file-open.ts b/src/renderer/src/components/editor/editor-dropped-file-open.ts index b925fa2af10..052d355878f 100644 --- a/src/renderer/src/components/editor/editor-dropped-file-open.ts +++ b/src/renderer/src/components/editor/editor-dropped-file-open.ts @@ -1,35 +1,33 @@ -import type { EditorFileDropDestination } from './editor-file-drop-destination' import { toast } from 'sonner' import { detectLanguage } from '../../../../shared/editor-language/editor-language-detect' import { isPathInsideWorktree, toWorktreeRelativePath } from '../../../../shared/terminal/links/terminal-links' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { getConnectionId } from '@/lib/workspace/ownership/connection-context' import { basename, joinPath } from '@/lib/path' -import type { WorktreeRuntimeOwnerState } from '@/lib/workspace/ownership/worktree-runtime-owner-state' import { importExternalPathsToRuntime } from '@/runtime/files/imports/runtime-file-import-client' -import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' import { runtimeTargetEnvironmentId } from '@/runtime/rpc/targets/runtime-client-target' -import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' import { translate } from '@/i18n/i18n' import { describeSharedDropFailureReason } from '@/lib/files/drop/drop-skip-reason-copy' -import { captureWorktreeSshMutationExpectation } from '@/lib/ssh-mutation-expectation' +import { captureWorktreeSshMutationExpectation } from '@/runtime/hosts/ssh/ssh-mutation-expectation' import { statUserOpenedPath } from '@/lib/files/access/user-opened-local-path' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' import { DROP_STAGING_RELATIVE_DIR } from '../../../../shared/drop-staging-ignore' import { openDocumentInFloatingWorkspace } from '@/components/floating-terminal/open-document-in-floating-workspace' import { requireRuntimeTargetForFileOwner } from '@/lib/files/access/file-owner-runtime-target' import { parseExecutionHostId } from '../../../../shared/execution-host' -import { - isResolvedWorkspaceFileDragExecutionHost, - type WorkspaceFileDragSource -} from '@/lib/files/drop/workspace-file-drag' +import { isResolvedWorkspaceFileDragExecutionHost } from '@/lib/files/drop/workspace-file-drag' +import type { WorkspaceFileDragSource } from '@/lib/files/drop/workspace-file-drag' import { captureFileExplorerOperationGuard, getFileExplorerOperationOwner } from '../right-sidebar/file-explorer/navigation/file-explorer-operation-owner' +import type { EditorFileDropDestination } from './editor-file-drop-destination' +import type { WorktreeRuntimeOwnerState } from '@/lib/workspace/ownership/worktree-runtime-owner-state' +import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' +import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' export function shouldUploadRemoteEditorFileDrop( target: RuntimeClientTarget, diff --git a/src/renderer/src/components/editor/git-graph/git-graph-history-controller.ts b/src/renderer/src/components/editor/git-graph/git-graph-history-controller.ts index cd5a139ea05..359bdde7739 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-history-controller.ts +++ b/src/renderer/src/components/editor/git-graph/git-graph-history-controller.ts @@ -268,15 +268,18 @@ export class GitGraphHistoryController { if (!current()) { return undefined } - const result = error !== undefined ? previous : (accumulated ?? previous) - const selection = this.view.getState().selectedId - const selectedId = - result?.items.find((item) => item.id === selection)?.id ?? result?.items[0]?.id - const selectionGone = selection !== undefined && selection !== selectedId + // A page that added nothing keeps the result identity, so viewport paging can't repeat it. + const stalled = + append && !recovered && accumulated?.hasMore && items.length === previous?.items.length + const result = error !== undefined || stalled ? previous : (accumulated ?? previous) + const selected = this.view.getState().selectedId + const selectedId = result?.items.find(({ id }) => id === selected)?.id ?? result?.items[0]?.id + const selectionGone = selected !== undefined && selected !== selectedId if (selectionGone) { this.actions.cancel() this.scrollOffset = 0 } + this.pending = undefined this.view.setState({ result, error, diff --git a/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx b/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx index 61a4f918161..e4340803411 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx @@ -13,7 +13,11 @@ import * as commitSupport from '@/runtime/source-control/git/git-commit-actions- import { useGitGraphHistory } from './use-git-graph-history' import type { GitHistoryResult } from '../../../../../shared/git/history/git-history-types' -const { getHistory, getRefs } = vi.hoisted(() => ({ getHistory: vi.fn(), getRefs: vi.fn() })) +const { getHistory, getRefs, viewport } = vi.hoisted(() => ({ + getHistory: vi.fn(), + getRefs: vi.fn(), + viewport: { rows: 20, rendered: Infinity } +})) vi.mock('@/runtime/source-control/git/runtime-git-status-client', async (original) => ({ ...(await original()), getRuntimeGitHistory: getHistory, @@ -27,7 +31,15 @@ vi.mock('@tanstack/react-virtual', () => ({ useVirtualizer: (options: { count: number; getScrollElement: () => HTMLElement | null }) => ({ getTotalSize: () => options.count * 28, getVirtualItems: () => - Array.from({ length: options.count }, (_, index) => ({ index, start: index * 28 })), + Array.from({ length: Math.min(options.count, viewport.rendered) }, (_, index) => ({ + index, + start: index * 28 + })), + get range() { + return options.count + ? { startIndex: 0, endIndex: Math.min(options.count, viewport.rows) - 1 } + : null + }, measureElement: () => {}, scrollToIndex: (index: number) => { const element = options.getScrollElement() @@ -53,6 +65,8 @@ beforeEach(() => { afterEach(async () => { await act(async () => root.unmount()) root = createRoot(container) + viewport.rows = 20 + viewport.rendered = Infinity disposeGitGraphHistory(`${workspaceId}::git-graph`) useAppStore.setState(initialState, true) vi.restoreAllMocks() @@ -520,3 +534,115 @@ it('keeps the confirm strip across tab switches, discarding it on navigation, fi await act(async () => root.render(render())) expect(container.textContent).not.toContain('Revert a?') }) +const longHistory = Array.from({ length: 200 }, (_, index) => ({ + id: `commit-${index}`, + subject: `Commit ${index}`, + message: `Commit ${index}`, + parentIds: [] +})) +const longPage = (skip: number): GitHistoryResult => ({ + ...result, + refs: 'all', + historyToken: 'long', + items: longHistory.slice(skip, skip + 50), + hasMore: skip + 50 < longHistory.length +}) +const renderTab = () => + act(async () => + root.render( + + + + ) + ) +const loadedCount = () => gitGraphHistoryForTab(workspaceId).view.getState().result?.items.length + +it('pages a pane taller than the loaded commits until they overflow it, and again when it grows', async () => { + viewport.rows = 120 + getHistory.mockReset().mockImplementation(async (_owner, options) => longPage(options.skip)) + await renderTab() + expect(loadedCount()).toBe(150) + viewport.rows = 400 + await renderTab() + expect(loadedCount()).toBe(200) + expect(container.textContent).not.toContain('Load more') +}) + +it('leaves a failed page to Load more, even after switching tabs away and back', async () => { + viewport.rows = Infinity + getHistory + .mockReset() + .mockResolvedValueOnce(longPage(0)) + .mockRejectedValueOnce(new Error('network down')) + .mockImplementation(async (_owner, options) => longPage(options.skip)) + await renderTab() + await act(async () => root.render(
Another tab
)) + await renderTab() + expect(loadedCount()).toBe(50) + expect(container.textContent).toContain('network down') + await act(async () => { + Array.from(container.querySelectorAll('button')) + .find((button) => button.textContent === 'Load more')! + .click() + }) + expect(loadedCount()).toBe(200) +}) + +it('stops paging on a page that adds no commits, and ends on an empty last page', async () => { + viewport.rows = Infinity + getHistory.mockReset().mockResolvedValue(longPage(0)) + await renderTab() + await renderTab() + expect(loadedCount()).toBe(50) + expect(getHistory).toHaveBeenCalledTimes(2) + getHistory.mockResolvedValue({ ...longPage(0), items: [], hasMore: false }) + await act(async () => { + await gitGraphHistoryForTab(workspaceId).loadMore() + }) + expect(container.textContent).not.toContain('Load more') +}) + +it.each([50_000, 500_000])( + 'releases %i commits of replaced history while the pane stays mounted', + async (count) => { + viewport.rows = Infinity + viewport.rendered = 40 + getHistory + .mockReset() + .mockImplementationOnce(async () => ({ + ...result, + refs: 'all', + hasMore: true, + items: Array.from({ length: count }, (_, index) => ({ + id: `old-${index}`, + subject: `Old ${index}`, + message: `Old ${index}`, + parentIds: [] + })) + })) + .mockRejectedValueOnce(new Error('network down')) + .mockResolvedValue({ ...result, refs: 'head' }) + await renderTab() + const replaced = (() => { + const loaded = gitGraphHistoryForTab(workspaceId).view.getState().result! + expect(loaded.items).toHaveLength(count) + return new WeakRef(loaded) + })() + await act(async () => + useAppStore.setState({ gitGraphFiltersByWorktree: { [workspaceId]: 'head' } }) + ) + await act(async () => { + await gitGraphHistoryForTab(workspaceId).settledResult() + }) + expect(loadedCount()).toBe(1) + getHistory.mockReset() + if (typeof globalThis.gc !== 'function') { + throw new Error('Run with the repository Vitest --expose-gc config') + } + for (let round = 0; round < 3; round++) { + await new Promise((resolve) => setImmediate(resolve)) + globalThis.gc() + } + expect(replaced.deref()).toBeUndefined() + } +) diff --git a/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx b/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx index 4e581dd97fc..359c7035182 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx @@ -3,7 +3,7 @@ import { GitGraphCommitActionControls, GitGraphCommitConfirmStrip } from './git-graph-commit-action-controls' -import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { useSidebarResize } from '@/hooks/useSidebarResize' import { useVirtualizer } from '@tanstack/react-virtual' import { RefreshCw } from 'lucide-react' @@ -20,18 +20,21 @@ import { } from '../../../../../shared/git/history/git-history-graph' import { useGitGraphHistory, gitGraphFilterSupported } from './use-git-graph-history' import { GitGraphFilter } from './git-graph-filter' +import { loadMoreInView } from './git-graph-viewport-paging' import { GitGraphDetails } from './git-graph-details' import { GitGraphRefs, useGitGraphWorkspaces } from './git-graph-ref-menu' import { cn } from '@/lib/class-names' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' const sameGroup = () => undefined +// About 200px of rows, so scrolling fetches before the end shows. +const PAGE_AHEAD_ROWS = 8 export function GitGraphTab({ worktreeId }: { worktreeId: string }) { const t = useTranslate() const intlLocale = useIntlLocale() const history = useGitGraphHistory(worktreeId) - const { result, scope, selectedId, revealId, controller } = history + const { result, scope, selectedId, revealId, controller, loading } = history const commitActionSupport = useGitCommitActionsSupport( scope?.target ?? null, scope?.route.executionHostId ?? undefined @@ -88,6 +91,16 @@ export function GitGraphTab({ worktreeId }: { worktreeId: string }) { overscan: 12, getItemKey: (index) => rows[index]!.historyItem.id }) + const virtualItems = virtualizer.getVirtualItems() + // Null while the pane has no height; read after getVirtualItems() recomputes it. + const lastVisibleIndex = virtualizer.range?.endIndex ?? -1 + const endInView = lastVisibleIndex >= 0 && lastVisibleIndex >= rows.length - 1 - PAGE_AHEAD_ROWS + useEffect(() => { + // Viewport demand, not scroll events: page whenever the end of loaded rows is in view. + if (endInView) { + loadMoreInView(controller, result) + } + }, [endInView, result, loading, controller]) const selected = result?.items.find((item) => item.id === selectedId) useLayoutEffect(() => { if (scroll.current) { @@ -189,20 +202,13 @@ export function GitGraphTab({ worktreeId }: { worktreeId: string }) { if (element) { controller.scrollOffset = element.scrollTop } - if ( - element && - element.scrollHeight - element.scrollTop - element.clientHeight < 200 && - !history.loading - ) { - void history.loadMore() - } }} >
- {virtualizer.getVirtualItems().map((virtualRow) => { + {virtualItems.map((virtualRow) => { const viewModel = rows[virtualRow.index]! const item = viewModel.historyItem return ( diff --git a/src/renderer/src/components/editor/git-graph/git-graph-viewport-paging.ts b/src/renderer/src/components/editor/git-graph/git-graph-viewport-paging.ts new file mode 100644 index 00000000000..1b1145571a7 --- /dev/null +++ b/src/renderer/src/components/editor/git-graph/git-graph-viewport-paging.ts @@ -0,0 +1,18 @@ +import type { GitGraphHistoryController } from './git-graph-history-controller' +import type { GitHistoryResult } from '../../../../../shared/git/history/git-history-types' + +// Keyed by result so it outlives tab remounts without keeping replaced history alive. +const pagedInView = new WeakSet() + +/** Asks for the next page once per result; a failed or no-progress page keeps its result, so only Load more or Refresh retries it. */ +export function loadMoreInView( + controller: GitGraphHistoryController, + rendered: GitHistoryResult | undefined +): void { + const { result, loading } = controller.view.getState() + // Only page the result whose rows were measured in view; a newer one gets its own check. + if (result && result === rendered && result.hasMore && !loading && !pagedInView.has(result)) { + pagedInView.add(result) + void controller.loadMore() + } +} diff --git a/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-link-actions.ts b/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-link-actions.ts index 8da806ffd8d..e0df54cdc63 100644 --- a/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-link-actions.ts +++ b/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-link-actions.ts @@ -6,7 +6,7 @@ import { isLocalPathOpenBlocked, showLocalPathOpenBlockedToast } from '@/lib/files/os-open/local-path-open-guard' -import { getLinkSourceLocalOpenOwner } from '@/lib/link-source-local-open-owner' +import { getLinkSourceLocalOpenOwner } from '@/lib/links/ownership/link-source-local-open-owner' import { openHttpLink } from '@/lib/browser/navigation/http-link-routing' import { translate } from '@/i18n/i18n' import { requireRuntimeTargetForFileOwner } from '@/lib/files/access/file-owner-runtime-target' diff --git a/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-system-link-action.ts b/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-system-link-action.ts index 65b1398fe15..2c13bc007a2 100644 --- a/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-system-link-action.ts +++ b/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-system-link-action.ts @@ -5,19 +5,19 @@ import { showLocalPathOpenBlockedToast } from '@/lib/files/os-open/local-path-open-guard' import { openHttpLink } from '@/lib/browser/navigation/http-link-routing' -import { getLinkSourceLocalOpenOwner } from '@/lib/link-source-local-open-owner' +import { getLinkSourceLocalOpenOwner } from '@/lib/links/ownership/link-source-local-open-owner' import { useAppStore } from '@/store/index' import { absolutePathToFileUri, resolveMarkdownLinkTarget } from '../../markdown/link-routing/markdown-internal-links' import { openMarkdownFileLinkWithSystemDefault } from '../../markdown/link-routing/markdown-file-link-system-open' -import type { MarkdownPreviewLinkContext } from './markdown-preview-link-actions' import { getMarkdownPreviewLinkTarget, isMarkdownPreviewSystemBrowserModifier, resolveMarkdownPreviewHttpOpenOptions } from '../../markdown/link-routing/markdown-preview-links' +import type { MarkdownPreviewLinkContext } from './markdown-preview-link-actions' export function handleMarkdownPreviewSystemLinkClick({ event, diff --git a/src/renderer/src/components/editor/notebook/outputs/IpynbCellOutputs.tsx b/src/renderer/src/components/editor/notebook/outputs/IpynbCellOutputs.tsx index 64854e84dc6..f4e8908f551 100644 --- a/src/renderer/src/components/editor/notebook/outputs/IpynbCellOutputs.tsx +++ b/src/renderer/src/components/editor/notebook/outputs/IpynbCellOutputs.tsx @@ -1,16 +1,17 @@ -import type { ITheme } from '@xterm/xterm' import { cn } from '@/lib/class-names' -import '@/lib/terminal-theme' -import { getTheme } from '@/lib/terminal-themes-data' +import '@/lib/terminal/appearance/terminal-theme' +import { getTheme } from '@/lib/terminal/appearance/terminal-themes-data' import { DEFAULT_TERMINAL_THEME_DARK, DEFAULT_TERMINAL_THEME_LIGHT } from '../../../../../../shared/terminal-themes/terminal-theme-selection' import { IpynbMarkdownCell } from '../cells/IpynbCellEditor' import { IpynbHtmlOutput } from './IpynbHtmlOutput' -import { parseAnsiSegments, type AnsiColor } from './ipynb-ansi' -import type { IpynbCell, IpynbOutput, IpynbOutputItem } from '../document/ipynb-parse' +import { parseAnsiSegments } from './ipynb-ansi' +import type { AnsiColor } from './ipynb-ansi' import { useDocumentDarkTheme } from '@/hooks/use-document-dark-theme' +import type { ITheme } from '@xterm/xterm' +import type { IpynbCell, IpynbOutput, IpynbOutputItem } from '../document/ipynb-parse' const ANSI_PALETTE_KEYS = [ 'black', diff --git a/src/renderer/src/components/editor/open-editor-html-preview.test.ts b/src/renderer/src/components/editor/open-editor-html-preview.test.ts index 63d543b1e44..752bf9141e6 100644 --- a/src/renderer/src/components/editor/open-editor-html-preview.test.ts +++ b/src/renderer/src/components/editor/open-editor-html-preview.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { createStoreCascadesMockApi } from '@/store/testing/app-store-cascade-api.test-fixture' import { EDITOR_OWNER, @@ -10,7 +10,7 @@ import { seedBrowserLinkTestStore, WORKSPACE } from '@/lib/browser/navigation/browser-link-open.test-fixture' -import { beginLinkOpenRequest } from '@/lib/link-open-request' +import { beginLinkOpenRequest } from '@/lib/links/link-open-request' import { registerEditorFrameFlush } from './save/flush/editor-pending-flush' import { openEditorHtmlPreview } from './open-editor-html-preview' @@ -214,25 +214,6 @@ it('refuses a local preview when the file gains remote host evidence during its expect(useAppStore.getState().browserTabsByWorktree[WORKSPACE] ?? []).toEqual([]) }) -it.each(['refused', 'rejected'] as const)( - 'keeps the editor selected when its guest flush is %s', - async (failure) => { - const unregister = registerEditorFrameFlush('report', () => - failure === 'refused' ? Promise.resolve(false) : Promise.reject(new Error('flush failed')) - ) - try { - await openEditorHtmlPreview('report', 'source') - const state = useAppStore.getState() - expect(state.browserTabsByWorktree[WORKSPACE] ?? []).toEqual([]) - expect( - state.groupsByWorktree[WORKSPACE]?.find((group) => group.id === 'a')?.activeTabId - ).toBe('source') - } finally { - unregister() - } - } -) - it('cancels preview when its editor tab closes but the file stays open in another tab', async () => { useAppStore.setState((state) => ({ unifiedTabsByWorktree: { diff --git a/src/renderer/src/components/editor/open-editor-html-preview.ts b/src/renderer/src/components/editor/open-editor-html-preview.ts index 320351d3638..f846736d618 100644 --- a/src/renderer/src/components/editor/open-editor-html-preview.ts +++ b/src/renderer/src/components/editor/open-editor-html-preview.ts @@ -1,5 +1,5 @@ import { toast } from 'sonner' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { editorViewPlacement, editorViewTab @@ -8,8 +8,8 @@ import { openFileInBrowserTab } from '@/lib/browser/documents/file-preview' import { resolveFileBrowserLinkExecutionHostId } from '@/lib/browser/documents/file-preview-link-open' import { captureBrowserLinkReveal } from '@/lib/browser/navigation/browser-link-reveal' import { createBrowserLinkHostMatcher } from '@/lib/browser/navigation/browser-link-owner' -import { beginLinkOpenRequest, subscribeLinkOpenRequests } from '@/lib/link-open-request' -import { captureLinkOpenIntent } from '@/lib/link-open-intent' +import { beginLinkOpenRequest, subscribeLinkOpenRequests } from '@/lib/links/link-open-request' +import { captureLinkOpenIntent } from '@/lib/links/placement/link-open-intent' import { flushEditorFrames } from './save/flush/editor-pending-flush' export async function openEditorHtmlPreview( diff --git a/src/renderer/src/components/editor/review-note-delivery/NotesSendMenu.tsx b/src/renderer/src/components/editor/review-note-delivery/NotesSendMenu.tsx index 7b09978a250..dd416b17092 100644 --- a/src/renderer/src/components/editor/review-note-delivery/NotesSendMenu.tsx +++ b/src/renderer/src/components/editor/review-note-delivery/NotesSendMenu.tsx @@ -22,7 +22,7 @@ import { holdNotesForSend, isNoteInFlight, useNotesInFlightVersion -} from '@/lib/notes-send-in-flight' +} from '@/components/notes/delivery/notes-send-in-flight' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { recomputeOn } from '@/lib/recompute-on' diff --git a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert.ts b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert.ts index 78a965234d9..baa7c77cdfd 100644 --- a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert.ts +++ b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert.ts @@ -1,4 +1,3 @@ -import type { Editor } from '@tiptap/react' import { toast } from 'sonner' import { dirname, basename } from '@/lib/path' import { getConnectionId } from '@/lib/workspace/ownership/connection-context' @@ -10,18 +9,19 @@ import { } from '@/lib/editor/file-operations/editor-file-operation-owner' import { editorTabDocumentFolderAccess } from '@/lib/files/access/local-file-access' import { requireRuntimeTargetForFileOwner } from '@/lib/files/access/file-owner-runtime-target' -import { captureDirectSshMutationExpectation } from '@/lib/ssh-mutation-expectation' +import { captureDirectSshMutationExpectation } from '@/runtime/hosts/ssh/ssh-mutation-expectation' import { translate } from '@/i18n/i18n' import { parseWorkspaceKey } from '../../../../../../shared/workspace-scope' import { extractIpcErrorMessage } from './rich-markdown-ipc-error-message' import { buildRichMarkdownImageInsertContent } from './rich-markdown-image-insert-content' import { showRichMarkdownImageInsertionCanceled } from './rich-markdown-image-insertion-feedback' -import type { RichMarkdownImageInsertionRange } from './rich-markdown-image-insertion-target' import { richMarkdownClipboardInsertionOrderKey } from '../clipboard/rich-markdown-clipboard-insertion-order' import { selectFolderWorkspaces, selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' +import type { Editor } from '@tiptap/react' +import type { RichMarkdownImageInsertionRange } from './rich-markdown-image-insertion-target' import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' import type { LocalFileAccess } from '../../../../../../shared/file-access/local-file-access' diff --git a/src/renderer/src/components/editor/rich-markdown/links/rich-markdown-editor-click-routing.ts b/src/renderer/src/components/editor/rich-markdown/links/rich-markdown-editor-click-routing.ts index 7878353d3d5..bf4e6a7d2bc 100644 --- a/src/renderer/src/components/editor/rich-markdown/links/rich-markdown-editor-click-routing.ts +++ b/src/renderer/src/components/editor/rich-markdown/links/rich-markdown-editor-click-routing.ts @@ -1,8 +1,4 @@ -import type { MutableRefObject } from 'react' -import type { Editor } from '@tiptap/react' -import type { EditorView } from '@tiptap/pm/view' import { toast } from 'sonner' -import type { HttpLinkSourceOwner } from '@/lib/browser/navigation/http-link-routing' import { httpLinkActionDestinationsFor, openRoutedHttpLink @@ -17,7 +13,7 @@ import { isLocalPathOpenBlocked, showLocalPathOpenBlockedToast } from '@/lib/files/os-open/local-path-open-guard' -import { getLinkSourceLocalOpenOwner } from '@/lib/link-source-local-open-owner' +import { getLinkSourceLocalOpenOwner } from '@/lib/links/ownership/link-source-local-open-owner' import { absolutePathToFileUri as toFileUrlForOsEscape, resolveMarkdownLinkTarget @@ -25,13 +21,15 @@ import { import { openMarkdownFileLinkWithSystemDefault } from '../../markdown/link-routing/markdown-file-link-system-open' import { scrollToAnchorInEditor } from '../../markdown/navigation/markdown-anchor-scroll' import { getRichMarkdownCommentAtPos } from '../review/rich-markdown-review-annotations' -import type { DiffComment } from '../../../../../../shared/diff-comment-types' import { toRuntimeExecutionHostId } from '../../../../../../shared/execution-host' import { translate } from '@/i18n/i18n' -import { - classifyHtmlSuperscriptLinkAction, - type RichMarkdownHtmlSuperscriptLinkContext -} from '../citations/rich-markdown-html-superscript-link-context' +import { classifyHtmlSuperscriptLinkAction } from '../citations/rich-markdown-html-superscript-link-context' +import type { RichMarkdownHtmlSuperscriptLinkContext } from '../citations/rich-markdown-html-superscript-link-context' +import type { MutableRefObject } from 'react' +import type { Editor } from '@tiptap/react' +import type { EditorView } from '@tiptap/pm/view' +import type { HttpLinkSourceOwner } from '@/lib/browser/navigation/http-link-routing' +import type { DiffComment } from '../../../../../../shared/diff-comment-types' export type ActivateMarkdownLink = ( href: string, diff --git a/src/renderer/src/components/feature-tips/FeatureTipsModal.tsx b/src/renderer/src/components/feature-tips/FeatureTipsModal.tsx index 3b4ce1502c2..a9d16fdca70 100644 --- a/src/renderer/src/components/feature-tips/FeatureTipsModal.tsx +++ b/src/renderer/src/components/feature-tips/FeatureTipsModal.tsx @@ -5,7 +5,7 @@ import { ORCHESTRATION_ENABLED_STORAGE_KEY, ORCHESTRATION_SETUP_DISMISSED_STORAGE_KEY, notifyOrchestrationSetupStateChanged -} from '@/lib/orchestration-setup-state' +} from '@/components/orchestration/setup/orchestration-setup-state' import { useAppStore } from '@/store/index' import { ChatUiHereTipDialog } from './ChatUiHereTipDialog' import { diff --git a/src/renderer/src/components/feature-wall/FeatureWallBrowserAction.tsx b/src/renderer/src/components/feature-wall/FeatureWallBrowserAction.tsx index f7c96eec088..fe369f2c93e 100644 --- a/src/renderer/src/components/feature-wall/FeatureWallBrowserAction.tsx +++ b/src/renderer/src/components/feature-wall/FeatureWallBrowserAction.tsx @@ -5,7 +5,6 @@ import { useOnboardingSkillRuntime } from '@/hooks/skills/runtime/use-onboarding import { FeatureSetupInlineTerminal } from '../onboarding/FeatureSetupInlineTerminal' import { buildAgentFeatureSkillInstallCommand } from '@/lib/skills/installation/agent-feature-install-commands' import { buildSkillCommandForRuntime } from '../../lib/skills/runtime/skill-runtime-command' -import type { OnboardingFeatureSetupRuntimeContext } from '../onboarding/onboarding-feature-setup-runtime' import { useCallback, useState } from 'react' import { ArrowUpRight, Download, Loader2 } from 'lucide-react' import { toast } from 'sonner' @@ -22,14 +21,15 @@ import { import { BundledSkillInstallStatus } from '../skills/setup/BundledSkillInstallStatus' import { onboardingFeatureSetupRunTelemetry, - runOnboardingFeatureSetup, - type OnboardingFeatureSetupSelection + runOnboardingFeatureSetup } from '../onboarding/onboarding-feature-setup' +import type { OnboardingFeatureSetupSelection } from '../onboarding/onboarding-feature-setup' import { promptForSetupGuideProject, useSetupTargetWorktree } from './FeatureWallSetupWorkflowActions' -import { getClientCreationActionPolicy } from '@/lib/client-creation-action-policy' +import { getClientCreationActionPolicy } from '@/lib/workspace/creation/surface-policy/client-creation-action-policy' +import type { OnboardingFeatureSetupRuntimeContext } from '../onboarding/onboarding-feature-setup-runtime' export function BrowserAction(props: { done: boolean }): React.JSX.Element { const t = useTranslate() diff --git a/src/renderer/src/components/feature-wall/use-feature-wall-task-source-presentation.ts b/src/renderer/src/components/feature-wall/use-feature-wall-task-source-presentation.ts index b927c969e98..075ee1243b8 100644 --- a/src/renderer/src/components/feature-wall/use-feature-wall-task-source-presentation.ts +++ b/src/renderer/src/components/feature-wall/use-feature-wall-task-source-presentation.ts @@ -1,9 +1,10 @@ import { useEffect } from 'react' -import type { FeatureWallWorkflow } from '../../../../shared/feature-wall-workflows' -import { useAppStore } from '@/store' -import { getLocalPreflightContext, localPreflightContextKey } from '@/lib/local-preflight-context' +import { useAppStore } from '@/store/index' +import { getLocalPreflightContext } from '@/runtime/hosts/preflight/local-preflight-context' import { getProviderRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context' import { deriveIntegrationConnectionStatus } from './use-integration-connection-status' +import type { FeatureWallWorkflow } from '../../../../shared/feature-wall-workflows' +import { localPreflightContextKey } from '../../runtime/hosts/preflight/local-preflight-context-key' export type FeatureWallTaskSourcePresentation = { workflow: FeatureWallWorkflow diff --git a/src/renderer/src/components/feature-wall/use-integration-connection-status.ts b/src/renderer/src/components/feature-wall/use-integration-connection-status.ts index 39b9eee1736..8aaedf5efa1 100644 --- a/src/renderer/src/components/feature-wall/use-integration-connection-status.ts +++ b/src/renderer/src/components/feature-wall/use-integration-connection-status.ts @@ -1,6 +1,7 @@ -import { useAppStore } from '@/store' -import { getLocalPreflightContext, localPreflightContextKey } from '@/lib/local-preflight-context' +import { useAppStore } from '@/store/index' +import { getLocalPreflightContext } from '@/runtime/hosts/preflight/local-preflight-context' import { getProviderRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context' +import { localPreflightContextKey } from '../../runtime/hosts/preflight/local-preflight-context-key' export type IntegrationStepState = 'active' | 'done' | 'upcoming' diff --git a/src/renderer/src/components/floating-terminal/FloatingTerminalPanelSurface.tsx b/src/renderer/src/components/floating-terminal/FloatingTerminalPanelSurface.tsx index cccb6558352..9eab191f6d4 100644 --- a/src/renderer/src/components/floating-terminal/FloatingTerminalPanelSurface.tsx +++ b/src/renderer/src/components/floating-terminal/FloatingTerminalPanelSurface.tsx @@ -3,7 +3,7 @@ import { TabGroupSplitNodeTree } from '@/components/tab-group/TabGroupSplitNodeT import { WorkspaceTabDragLayer } from '@/components/tab-group/WorkspaceTabDragLayer' import { WorkspacePaneOverlayLayers } from '@/components/WorkspacePaneOverlayLayers' import { isTerminalImeInputContextRefreshing } from '@/components/terminal-pane/input/ime/terminal-ime-input-context-refresh' -import { buildDuplicatedBrowserTabOptions } from '@/lib/duplicate-browser-tab-options' +import { buildDuplicatedBrowserTabOptions } from '@/lib/browser/workspace/duplicate-browser-tab-options' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' import { FloatingTerminalEmptyState } from './FloatingTerminalEmptyState' import { renderFloatingTerminalOrchestrationCard } from './FloatingTerminalOrchestrationCard' diff --git a/src/renderer/src/components/floating-terminal/floating-workspace-tab-creation.ts b/src/renderer/src/components/floating-terminal/floating-workspace-tab-creation.ts index 37009a22a4e..95e79de813c 100644 --- a/src/renderer/src/components/floating-terminal/floating-workspace-tab-creation.ts +++ b/src/renderer/src/components/floating-terminal/floating-workspace-tab-creation.ts @@ -2,11 +2,11 @@ import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' import { createUntitledMarkdownFileWithTemplateSelection } from '../../lib/editor/file-operations/create-untitled-markdown' import { getConnectionId } from '../../lib/workspace/ownership/connection-context' import { detectLanguage } from '../../../../shared/editor-language/editor-language-detect' -import type { AppState } from '@/store/types' import { focusTerminalTabSurface } from '../terminal-pane/input/focus/focus-terminal-tab-surface' import { createNonSecureContextUuid as createBrowserUuid } from '../../../../shared/non-secure-context-uuid' import { translate } from '@/i18n/i18n' -import { assertClientCreationActionAvailable } from '../../lib/client-creation-action-policy' +import { assertClientCreationActionAvailable } from '../../lib/workspace/creation/surface-policy/client-creation-action-policy' +import type { AppState } from '@/store/types' type FloatingWorkspaceTerminalStore = Pick diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-create-actions.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-create-actions.ts index b69f668cf45..dd99ef0b024 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-create-actions.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-create-actions.ts @@ -3,7 +3,7 @@ import { toast } from 'sonner' import { resolveGroupTabFromVisibleId } from '@/components/tab-group/tab-group-visible-id' import { getConnectionId } from '@/lib/workspace/ownership/connection-context' import { createUntitledMarkdownFileWithTemplateSelection } from '@/lib/editor/file-operations/create-untitled-markdown' -import { ensureClientCreationActionAllowed } from '@/lib/client-creation-action-error' +import { ensureClientCreationActionAllowed } from '@/lib/workspace/creation/surface-policy/client-creation-action-error' import { openDocumentInFloatingWorkspace } from '@/components/floating-terminal/open-document-in-floating-workspace' import { extractIpcErrorMessage } from '@/runtime/errors/ipc-error' import { focusTerminalTabSurface } from '@/components/terminal-pane/input/focus/focus-terminal-tab-surface' diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-orchestration-dismissal.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-orchestration-dismissal.ts index f585766aa9c..abb6924d8b0 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-orchestration-dismissal.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-orchestration-dismissal.ts @@ -2,7 +2,7 @@ import { useCallback } from 'react' import { ORCHESTRATION_SETUP_DISMISSED_STORAGE_KEY, notifyOrchestrationSetupStateChanged -} from '@/lib/orchestration-setup-state' +} from '@/components/orchestration/setup/orchestration-setup-state' import type { FloatingTerminalPanelLocalState } from './use-floating-terminal-panel-local-state' export function useFloatingTerminalOrchestrationDismissal({ diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-orchestration-visibility.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-orchestration-visibility.ts index dd730267828..2d149f8af44 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-orchestration-visibility.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-orchestration-visibility.ts @@ -2,9 +2,9 @@ import { useCallback, useEffect } from 'react' import { isOrcaCliAvailableOnPath } from '@/lib/skills/installation/agent-skill-cli-prerequisite' import { ORCHESTRATION_SETUP_STATE_EVENT, - hasOrchestrationSetupMarker, + isOrchestrationSetupEnabled, isOrchestrationSetupDismissed -} from '@/lib/orchestration-setup-state' +} from '@/components/orchestration/setup/orchestration-setup-state' import type { FloatingTerminalPanelLocalState } from './use-floating-terminal-panel-local-state' type FloatingTerminalOrchestrationVisibilityInput = Pick< @@ -22,7 +22,7 @@ export function useFloatingTerminalOrchestrationVisibility({ setShowOrchestrationSetup(false) return } - if (!hasOrchestrationSetupMarker()) { + if (!isOrchestrationSetupEnabled()) { setShowOrchestrationSetup(true) return } diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-local-state.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-local-state.ts index 237d4db1b77..f3e19c5584e 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-local-state.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-local-state.ts @@ -8,9 +8,9 @@ import type { } from './floating-terminal-panel-bounds' import { readPersistedFloatingTerminalPanelViewState } from './floating-terminal-panel-view-state' import { - hasOrchestrationSetupMarker, + isOrchestrationSetupEnabled, isOrchestrationSetupDismissed -} from '@/lib/orchestration-setup-state' +} from '@/components/orchestration/setup/orchestration-setup-state' import { readInitialPanelBounds, type FloatingTerminalPanelBoundsState @@ -35,7 +35,7 @@ export function useFloatingTerminalPanelLocalState() { const panelViewportSettled = useSettledPanelViewport() const [orchestrationDialogOpen, setOrchestrationDialogOpen] = useState(false) const [showOrchestrationSetup, setShowOrchestrationSetup] = useState( - () => !hasOrchestrationSetupMarker() && !isOrchestrationSetupDismissed() + () => !isOrchestrationSetupEnabled() && !isOrchestrationSetupDismissed() ) const restoreBoundsRef = useRef(null) const stagedBoundsRef = useRef(null) diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-shortcuts.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-shortcuts.ts index f4d6ce4e291..99a918ef649 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-shortcuts.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-shortcuts.ts @@ -1,6 +1,7 @@ -import { useCallback, useEffect, useRef, type KeyboardEvent as ReactKeyboardEvent } from 'react' +import { useCallback, useEffect, useRef } from 'react' +import type { KeyboardEvent as ReactKeyboardEvent } from 'react' import { isTerminalPaneCloseChord } from '@/components/terminal-pane/input/keyboard/terminal-shortcut-policy' -import { ensureClientCreationActionAllowed } from '@/lib/client-creation-action-error' +import { ensureClientCreationActionAllowed } from '@/lib/workspace/creation/surface-policy/client-creation-action-error' import { matchFloatingWorkspacePanelOwnedAction, matchFloatingWorkspacePanelShortcut @@ -10,13 +11,10 @@ import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform' import { requestTerminalTabRename } from '@/components/tab-bar/terminal-tab-rename-request' import { resolveTerminalAgentTabShortcut } from '@/components/terminal-agent-tab-shortcut' import { launchFloatingWorkspaceAgentShortcut } from '@/components/agent-tab-shortcut-launch' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' -import { - keybindingMatchesAction, - type KeybindingContext, - type KeybindingMatchOptions -} from '../../../../shared/keybindings' +import { keybindingMatchesAction } from '../../../../shared/keybindings' +import type { KeybindingContext, KeybindingMatchOptions } from '../../../../shared/keybindings' import type { FloatingPanelShortcutInput, FloatingPanelShortcutResolution, diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-store-state.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-store-state.ts index a167b0414fb..398d95877e1 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-store-state.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-panel-store-state.ts @@ -1,5 +1,5 @@ -import { getClientCreationActionPolicy } from '@/lib/client-creation-action-policy' -import { useAppStore } from '@/store' +import { getClientCreationActionPolicy } from '@/lib/workspace/creation/surface-policy/client-creation-action-policy' +import { useAppStore } from '@/store/index' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' import { selectFloatingTerminalPanelInputs } from './floating-terminal-panel-inputs' diff --git a/src/renderer/src/components/github-item-dialog/open-dialog/github-item-dialog.tsx b/src/renderer/src/components/github-item-dialog/open-dialog/github-item-dialog.tsx index 88bebcee075..2234ccdefa8 100644 --- a/src/renderer/src/components/github-item-dialog/open-dialog/github-item-dialog.tsx +++ b/src/renderer/src/components/github-item-dialog/open-dialog/github-item-dialog.tsx @@ -3,10 +3,10 @@ import { GitHubWorkItemTargetContext } from '../load-item-details/github-work-it import React, { useCallback, useEffect, useEffectEvent, useMemo, useState } from 'react' import { toast } from 'sonner' import { useAllWorktrees } from '@/store/slices/worktrees/listing/use-worktree-catalog' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { findGithubIssueWorkspaceAttachment } from '@/lib/work-items/github/github-work-item-workspace-attachment' import { activateAndRevealWorktree } from '@/lib/workspace/activation/worktree-activation' -import { getWorktreeAttachmentLabel } from '@/lib/worktree-attachment-label' +import { getWorktreeAttachmentLabel } from '@/lib/workspace/display/worktree-attachment-label' import { translate } from '@/i18n/i18n' import type { GitHubWorkItem } from '../../../../../shared/github/work-item-types' import type { GitHubItemDialogProps } from '../load-item-details/github-item-dialog-types' diff --git a/src/renderer/src/components/github-project/ProjectCellIssueType.tsx b/src/renderer/src/components/github-project/ProjectCellIssueType.tsx index ad0735c268e..73e08ffb789 100644 --- a/src/renderer/src/components/github-project/ProjectCellIssueType.tsx +++ b/src/renderer/src/components/github-project/ProjectCellIssueType.tsx @@ -3,10 +3,10 @@ import React, { useEffect, useMemo, useState } from 'react' import { useShallow } from 'zustand/react/shallow' import { CircleDot } from 'lucide-react' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' -import { useRepoSlugIndex } from '@/lib/repo-slug-index' +import { useRepoSlugIndex } from '@/lib/workspace/catalog/repo-slug-index' import { runtimeTargetForRepoOwner } from '@/lib/workspace/ownership/repo-runtime-owner' import { gitHubSlugApiForTarget } from '@/runtime/repository-github/github-slug-owner-api' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { useTranslate } from '@/i18n/use-translate' import type { GitHubIssueType, GitHubProjectRow } from '../../../../shared/github/project-types' import { chipStyle, colorHex, singleSelectChipColors } from './project-cell-chip-colors' diff --git a/src/renderer/src/components/github-project/useProjectRowActions.ts b/src/renderer/src/components/github-project/useProjectRowActions.ts index 6e92c2e2345..4bc7b7a9e66 100644 --- a/src/renderer/src/components/github-project/useProjectRowActions.ts +++ b/src/renderer/src/components/github-project/useProjectRowActions.ts @@ -1,8 +1,8 @@ import { useCallback, useState } from 'react' import { toast } from 'sonner' -import { useRepoSlugIndex } from '@/lib/repo-slug-index' +import { useRepoSlugIndex } from '@/lib/workspace/catalog/repo-slug-index' import { launchWorkItemDirect } from '@/lib/workspace/creation/work-item/launch-work-item-direct' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { translate } from '@/i18n/i18n' import { buildTaskSourceContextFromRepo } from '../../../../shared/work-items/task-source-context' import { githubProjectHost } from '../../../../shared/github/project-identity' diff --git a/src/renderer/src/components/github-project/useProjectViewTable.ts b/src/renderer/src/components/github-project/useProjectViewTable.ts index 6d910b7ec76..c6b727b8f68 100644 --- a/src/renderer/src/components/github-project/useProjectViewTable.ts +++ b/src/renderer/src/components/github-project/useProjectViewTable.ts @@ -4,7 +4,7 @@ import { toast } from 'sonner' import { useMountedRef } from '@/hooks/useMountedRef' import { useGitHubTaskProjectTable } from '@/hooks/useGitHubTaskItems' import { translate } from '@/i18n/i18n' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { projectViewCacheKey, projectViewSourceScope } from '@/store/github/cache/cache-identity' import type { GitHubProjectSettings, @@ -28,7 +28,7 @@ import { getVisibleProjectTable, type CachedVisibleProjectTable } from './project-visible-table-cache' -import { useRepoSlugIndex } from '@/lib/repo-slug-index' +import { useRepoSlugIndex } from '@/lib/workspace/catalog/repo-slug-index' export function useProjectViewTable( selectedRepoIds: ReadonlySet, diff --git a/src/renderer/src/components/integrations/source-control/source-control-preflight-card-status.ts b/src/renderer/src/components/integrations/source-control/source-control-preflight-card-status.ts index 7db6312828a..692e2aa5d76 100644 --- a/src/renderer/src/components/integrations/source-control/source-control-preflight-card-status.ts +++ b/src/renderer/src/components/integrations/source-control/source-control-preflight-card-status.ts @@ -1,12 +1,12 @@ import { useState } from 'react' import { useMountedRef } from '@/hooks/useMountedRef' -import { getLocalPreflightContext } from '@/lib/local-preflight-context' -import { localPreflightContextKey } from '@/lib/local-preflight-context-key' +import { getLocalPreflightContext } from '@/runtime/hosts/preflight/local-preflight-context' +import { localPreflightContextKey } from '@/runtime/hosts/preflight/local-preflight-context-key' import { useAppStore } from '@/store/index' -import { - getPreflightIntegrationStatuses, - type PreflightIntegrationStatuses, - type PreflightRefreshProvider +import { getPreflightIntegrationStatuses } from './integrations-pane-status' +import type { + PreflightIntegrationStatuses, + PreflightRefreshProvider } from './integrations-pane-status' type CliStatus = { diff --git a/src/renderer/src/components/native-chat-recovery/NativeChatResumeOnRestartModal.tsx b/src/renderer/src/components/native-chat-recovery/NativeChatResumeOnRestartModal.tsx index 569fbb2d98e..24a8fd71521 100644 --- a/src/renderer/src/components/native-chat-recovery/NativeChatResumeOnRestartModal.tsx +++ b/src/renderer/src/components/native-chat-recovery/NativeChatResumeOnRestartModal.tsx @@ -4,32 +4,32 @@ import { Button } from '../ui/button' import { Checkbox } from '../ui/checkbox' import { Dialog, DialogContent, DialogFooter } from '../ui/dialog' import { useAppStore } from '../../store/index' -import { useTranslate, type Translate } from '@/i18n/use-translate' -import { activateAiVaultStructuredSession } from '@/lib/activate-ai-vault-structured-session' +import { useTranslate } from '@/i18n/use-translate' +import type { Translate } from '@/i18n/use-translate' +import { activateAiVaultStructuredSession } from '@/lib/agent-session/open/activate-ai-vault-structured-session' import { ResumeOnRestartGroups } from './tree/NativeChatResumeOnRestartGroups' import { ResumeTreeRow } from './tree/NativeChatResumeTreeRow' import { resumeFailureGuidance, - resumeFailureSelectable, - type ResumeFailureAction + resumeFailureSelectable } from './failures/native-chat-resume-failure-guidance' +import type { ResumeFailureAction } from './failures/native-chat-resume-failure-guidance' import { resumeSelectionState, - toggleResumeSelection, - type ResumeCandidate, - type ResumeFailure + toggleResumeSelection } from './tree/native-chat-resume-on-restart-grouping' +import type { ResumeCandidate, ResumeFailure } from './tree/native-chat-resume-on-restart-grouping' import { useNativeChatRestartOffer, useNativeChatRestartResuming, useNativeChatRestartRun } from './offers/native-chat-resume-on-restart-store' -import type { NativeChatRestartStore } from './offers/native-chat-restart-runtime-store' import { useResumeRunPanel } from './runs/NativeChatResumeRunPanel' import { resumeRunFailures } from './runs/native-chat-resume-run-view' import { NativeChatResumeAutoNote } from './dialogs/NativeChatResumeAutoNote' import { NativeChatRemoteResumeActions } from './dialogs/NativeChatRemoteResumeActions' import { moveInTree } from './tree/native-chat-resume-tree-keys' +import type { NativeChatRestartStore } from './offers/native-chat-restart-runtime-store' /** Resume reattaches and sends a continuation, never the original user prompt; disclose this before sending. Automatic preference skips the prompt but uses the same host safety checks. * The store owns runs across dialog closes. Closing snoozes; Dismiss all deletes durable offers. Row Retry/Dismiss keep the dialog open, and settled runs cannot close a user-reopened dialog. Unretryable failures stay outside Resume. */ diff --git a/src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-bulk-progress.test.tsx b/src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-bulk-progress.test.tsx deleted file mode 100644 index 577e63211ee..00000000000 --- a/src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-bulk-progress.test.tsx +++ /dev/null @@ -1,150 +0,0 @@ -// @vitest-environment happy-dom -import { - createResumeModalFixture, - offered, - failure, - type RestartRpc, - type ResumeStatusStream -} from './native-chat-resume-modal.test-support' -import { act } from 'react' -import { expect, it, vi, type Mock } from 'vitest' -import { NativeChatResumeOnRestartModal } from '../NativeChatResumeRuntimeModal' - -import { NativeChatResumeStatusSegment } from '../../status-bar/NativeChatResumeStatusSegment' -import type { ResumeCandidate, ResumeFailure } from '../tree/native-chat-resume-on-restart-grouping' -import type { AgentSessionStatusSummary } from '../../../../../shared/agent-session/agent-session-wire' - -const rpc: Mock = vi.hoisted(() => vi.fn()) -const statusStream: ResumeStatusStream = vi.hoisted(() => ({ - emit: (_event: Parameters[0]) => {}, - snapshot: new Map() -})) -vi.mock('../../../runtime/native-chat/requests/structured-agent-session-call', () => ({ - callStructuredAgentSession: rpc -})) - -vi.mock('../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ - subscribeStructuredAgentSessionStatus: async ( - _target: unknown, - emit: (event: Parameters[0]) => void - ) => { - statusStream.emit = emit - emit({ type: 'snapshot', sessions: [...statusStream.snapshot.values()] }) - return { unsubscribe: () => {} } - } -})) -vi.mock('@/lib/activate-ai-vault-structured-session', () => ({ - activateAiVaultStructuredSession: vi.fn(async () => true) -})) -vi.mock('sonner', async () => - (await import('./native-chat-resume-sonner-mock.test-support')).resumeSonnerMock() -) - -const { mount, button, offerIds, runStatus } = createResumeModalFixture(rpc, statusStream) - -function emitPhase( - sessionId: string, - phase?: NonNullable['phase'] -): void { - statusStream.emit({ - type: 'status', - session: { - sessionId, - workspaceId: 'workspace', - agent: 'codex', - status: 'idle', - latestPrompt: '', - updatedAt: 1, - ...(phase ? { restartResume: { phase } } : {}) - } - }) -} - -it('keeps the run in flight after every feed verdict until the fallback list is published', async () => { - const answer = Promise.withResolvers<{ - continued: { sessionId: string; outcome: 'continued' }[] - }>() - const listing = Promise.withResolvers<{ sessions: ResumeCandidate[]; failed: ResumeFailure[] }>() - let reads = 0 - rpc.mockImplementation(async (_target, method) => - method === 'agentSession.restartContinue' - ? answer.promise - : reads++ === 0 - ? { sessions: offered, failed: [] } - : listing.promise - ) - await mount( - <> - - - - ) - await act(async () => button('Resume 2 chats').click()) - await act(async () => button('Resuming chats 0/2').click()) - await act(async () => { - for (const { sessionId } of offered) { - statusStream.emit({ - type: 'status', - session: { - sessionId, - workspaceId: 'workspace', - agent: 'codex', - status: 'idle', - latestPrompt: '', - updatedAt: 1, - restartResume: { phase: 'continued' } - } - }) - } - answer.resolve({ - continued: offered.map(({ sessionId }) => ({ sessionId, outcome: 'continued' })) - }) - }) - expect(button('Resuming chats 2/2')).toBeTruthy() - await act(async () => offered.forEach(({ sessionId }) => emitPhase(sessionId))) - expect(button('Resuming chats 2/2')).toBeTruthy() - expect(runStatus('Prompt a')).toBe('Prompt a: Resumed') - expect(button('Resuming…').disabled).toBe(true) - expect(document.body.textContent).not.toContain('chats to resume') - await act(async () => listing.resolve({ sessions: [], failed: [] })) - expect(offerIds()).toEqual([]) - expect(button('Done').disabled).toBe(false) - expect(document.body.textContent).not.toContain('Resuming chats') -}) - -it('retains success and refusal frames through cleanup before a delayed bulk reply', async () => { - const reply = Promise.withResolvers() - rpc.mockImplementation(async (_target, method) => - method === 'agentSession.restartResumable' ? { sessions: offered, failed: [] } : reply.promise - ) - await mount( - <> - - - - ) - await act(async () => button('Resume 2 chats').click()) - // Verdicts and cleanup can arrive together before React gets a render. - await act(async () => { - emitPhase('a', 'continued') - emitPhase('b', 'refused') - emitPhase('a') - emitPhase('b') - }) - expect(button('Resuming chats 2/2')).toBeTruthy() - await act(async () => button('Resuming chats 2/2').click()) - expect(runStatus('Prompt a')).toBe('Prompt a: Resumed') - expect(runStatus('Prompt b')).toBe('Prompt b: Couldn’t resume') - expect(document.querySelector('[role="dialog"]')?.textContent).toContain('Need you1') - await act(async () => - reply.resolve({ - sessions: [], - failed: [failure('b')], - continued: [ - { sessionId: 'a', outcome: 'continued' }, - { sessionId: 'b', outcome: 'refused' } - ] - }) - ) - expect(document.querySelector('[role="dialog"]')?.textContent).toContain('Resumed 1 of 2 chats') -}) diff --git a/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartAgentRow.tsx b/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartAgentRow.tsx index f7ca3dd3493..a5dc252b4b1 100644 --- a/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartAgentRow.tsx +++ b/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartAgentRow.tsx @@ -2,7 +2,7 @@ import { useContext } from 'react' import { AgentIcon } from '@/components/agent/icons/AgentIcon' import { agentTypeToIconAgent } from '../../../../../shared/agent-status/presentation/agent-type-icon-agent' import { formatAgentTypeLabel } from '../../../../../shared/agent-status/presentation/agent-type-label' -import { formatShortTimeAgo } from '@/lib/short-time-ago' +import { formatShortTimeAgo } from '@/lib/time-format/short-time-ago' import { useTranslate } from '@/i18n/use-translate' import type { ResumeCandidate, ResumeFailure } from './native-chat-resume-on-restart-grouping' import { diff --git a/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartGroups.tsx b/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartGroups.tsx index a83ecedd4ed..0ae75fa431c 100644 --- a/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartGroups.tsx +++ b/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartGroups.tsx @@ -5,7 +5,7 @@ import { ProjectOptionDetail } from '@/components/new-workspace/ProjectComboboxR import { WorktreeHostContextBadge } from '@/components/sidebar/workspace-card/host/WorktreeHostContextBadge' import { useSidebarHostScopeOptions } from '@/components/sidebar/worktree-list/controls/use-sidebar-host-scope-options' import { useTranslate } from '@/i18n/use-translate' -import { resolveWorktreeBranchLabel } from '@/lib/worktree-default-display-name' +import { resolveWorktreeBranchLabel } from '@/lib/workspace/display/worktree-default-display-name' import { getHostContextLabel } from '../../../../../shared/worktree/host-context-labels' import { LOCAL_EXECUTION_HOST_ID, diff --git a/src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-workspace-display.ts b/src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-workspace-display.ts index 961053d856e..67629d70813 100644 --- a/src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-workspace-display.ts +++ b/src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-workspace-display.ts @@ -1,5 +1,5 @@ import { dirname } from '@/lib/path' -import { resolveWorktreeDisplayName } from '@/lib/worktree-default-display-name' +import { resolveWorktreeDisplayName } from '@/lib/workspace/display/worktree-default-display-name' import { getWorktreePathBasenameFromId, splitWorktreeIdForFilesystem diff --git a/src/renderer/src/components/native-chat/appearance/NativeChatBackdrop.fixture.tsx b/src/renderer/src/components/native-chat/appearance/NativeChatBackdrop.fixture.tsx new file mode 100644 index 00000000000..7f56629b408 --- /dev/null +++ b/src/renderer/src/components/native-chat/appearance/NativeChatBackdrop.fixture.tsx @@ -0,0 +1,96 @@ +import { useEffect, useState } from 'react' +import { createPortal } from 'react-dom' +import { Terminal } from '@xterm/xterm' +import { defineFixture } from '../../../component-fixtures/component-fixture' +import { NativeChatPaneCover } from '../../terminal-pane/chat/NativeChatPaneCover' +import { + NATIVE_CHAT_APPEARANCE_ROOT_CLASS, + nativeChatAppearanceStyle +} from './native-chat-appearance-style' + +function ChatCanvas({ sample }: { sample: string }): React.JSX.Element { + return ( +
+
+
+ ) +} + +function TerminalPane({ + covered, + sample +}: { + covered: boolean + sample: string +}): React.JSX.Element { + const [container, setContainer] = useState(null) + const [terminal] = useState(() => new Terminal()) + useEffect(() => () => terminal.dispose(), [terminal]) + return ( +
+
+
+
+ {!covered &&
} + {covered && container + ? createPortal( + + + , + container + ) + : null} +
+ ) +} + +function Backdrops(): React.JSX.Element { + const [covered, setCovered] = useState(false) + useEffect(() => { + const root = document.documentElement + const previousMaterial = root.getAttribute('data-window-material') + const previousOpacity = root.style.getPropertyValue('--orca-window-surface-opacity') + root.dataset.windowMaterial = 'blur' + root.style.setProperty('--orca-window-surface-opacity', '0.3') + return () => { + if (previousMaterial === null) { + root.removeAttribute('data-window-material') + } else { + root.setAttribute('data-window-material', previousMaterial) + } + root.style.setProperty('--orca-window-surface-opacity', previousOpacity) + } + }, []) + const terminalBackground = 'color-mix(in srgb, var(--background) 30%, transparent)' + return ( + <> + +
+
+
+ +
+
+ + +
+
+ +
+
+ + ) +} + +export const material = defineFixture({ + width: 800, + render: () => +}) diff --git a/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.ts b/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.ts index 878ca97a5be..d01c4028497 100644 --- a/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.ts +++ b/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.ts @@ -1,17 +1,18 @@ import './native-chat-appearance.css' -import { useMemo, type CSSProperties } from 'react' +import { useMemo } from 'react' +import type { CSSProperties } from 'react' import { useShallow } from 'zustand/react/shallow' -import type { GlobalSettings } from '../../../../../shared/global-settings-types' import { resolveNativeChatAppearanceSettings } from '../../../../../shared/native-chat/native-chat-appearance-settings' import { resolveConfiguredTerminalColors } from '../../../../../shared/terminal-themes/terminal-theme-selection' import { MATCH_TERMINAL_APP_THEME } from '../../../../../shared/plugin-theme-settings' import { buildFontFamily } from '../../../../../shared/monospace-font-family' import { buildAppFontFamily } from '@/app-shell/appearance/app-font-family' import { resolveEditorFontStack } from '../../../../../shared/editor/editor-typography' -import { getSystemPrefersDark } from '@/lib/terminal-theme' +import { getSystemPrefersDark } from '@/lib/terminal/appearance/terminal-theme' import { isTerminalBackgroundLight } from '../../../../../shared/terminal-themes/terminal-title-contrast' import { useSystemPrefersDark } from '../../../hooks/theme/use-system-prefers-dark' import { terminalChatSelectionMix } from '@/app-shell/appearance/chat-selection-mix' +import type { GlobalSettings } from '../../../../../shared/global-settings-types' export const NATIVE_CHAT_APPEARANCE_ROOT_CLASS = 'native-chat-appearance bg-chat-canvas' // Bottom padding clears 20px control overhang; rail padding also covers its 34px overlay on macOS without scrollbar gutters. diff --git a/src/renderer/src/components/native-chat/appearance/native-chat-appearance.css b/src/renderer/src/components/native-chat/appearance/native-chat-appearance.css index ba550b8559c..28e22d1d2de 100644 --- a/src/renderer/src/components/native-chat/appearance/native-chat-appearance.css +++ b/src/renderer/src/components/native-chat/appearance/native-chat-appearance.css @@ -39,35 +39,31 @@ initial-value: 0px; } -/* Over a theme image (main.css) a chat that fills its pane paints the canvas once and the layers - under it go clear. The canvas follows Background Opacity, floored at 0.8 so body text stays near - 4.5:1 even over white or black pixels. A chat split beside terminals stays opaque, since the pane - manager paints the terminal color under every pane of the split. */ -:root[data-theme-background] [data-terminal-chat-view]:not(.has-multiple-panes) { +/* Chat keeps a readable canvas over either backdrop. Mixed splits retain their shared terminal + paint beneath it so neighboring terminals keep their background. */ +:root:is([data-theme-background], [data-window-material]) + [data-terminal-chat-pane]:not(.has-multiple-panes) { /* Beats the pane manager's inline split paint (pane-divider.ts applyRootBackground). */ background: transparent !important; } -:root[data-theme-background] - [data-terminal-chat-view]:not(.has-multiple-panes) +:root:is([data-theme-background], [data-window-material]) + [data-terminal-chat-pane] .native-chat-pane-shell { background-color: transparent; } /* The opaque cover used to hide the terminal and its banners (layers below its z-10); overlays above it stay. Opacity, not visibility, so the covered terminal can still take focus handoffs. */ -:root[data-theme-background] - [data-terminal-chat-view]:not(.has-multiple-panes) - .pane +:root:is([data-theme-background], [data-window-material]) + [data-terminal-chat-pane] + .pane:has(> .native-chat-pane-shell) > :is(.xterm-container, .session-restored-banner, .pane-top-banner) { opacity: 0; } -:root[data-theme-background] - :is( - [data-terminal-chat-view]:not(.has-multiple-panes), - [data-structured-agent-session-overlay-tab-id] - ) +:root:is([data-theme-background], [data-window-material]) + :is([data-terminal-chat-pane], [data-structured-agent-session-overlay-tab-id]) [data-native-chat-root] { --chat-pane: transparent; /* Text-bearing surfaces keep an opaque base, as in the light scheme. */ @@ -90,7 +86,14 @@ ); background-color: color-mix( in srgb, - var(--chat-canvas) calc(max(var(--orca-theme-background-surface-opacity), 0.8) * 100%), + var(--chat-canvas) + calc( + max( + var(--orca-theme-background-surface-opacity, var(--orca-window-surface-opacity, 1)), + 0.8 + ) * + 100% + ), transparent ); } diff --git a/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-external-attachments.ts b/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-external-attachments.ts index dfe8717a953..a9ec94c2539 100644 --- a/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-external-attachments.ts +++ b/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-external-attachments.ts @@ -1,13 +1,15 @@ import { captureNativeChatEditDraftDestination } from '../../drafts/native-chat-composer-draft-memory' import { useCallback, useLayoutEffect, useRef } from 'react' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { NATIVE_FILE_DROP_MAX_PATHS } from '../../../../../../shared/file-import/native-file-drop' import { isSameComposerWorkspace, - nativeChatAttachmentOwnerUnchanged, - type ComposerWorkspace, - type NativeChatAttachmentFocusOptions, - type NativeChatResolvedPathOptions + nativeChatAttachmentOwnerUnchanged +} from '../uploads/native-chat-resolved-path-ownership' +import type { + ComposerWorkspace, + NativeChatAttachmentFocusOptions, + NativeChatResolvedPathOptions } from '../uploads/native-chat-resolved-path-ownership' import { nativeChatAttachmentOwnerChangedNotice, @@ -18,21 +20,24 @@ import { import { resolveNativeChatAttachmentOwner, resolveNativeChatAttachmentOwnerForWorktree, - resolveNativeChatRuntimeSessionAttachmentOwner, - type NativeChatAttachmentOwner, - type NativeChatStructuredAttachmentSession + resolveNativeChatRuntimeSessionAttachmentOwner +} from '../uploads/native-chat-attachment-owner' +import type { + NativeChatAttachmentOwner, + NativeChatStructuredAttachmentSession } from '../uploads/native-chat-attachment-owner' - import { attachNativeChatSessionAttachmentPaths, - reserveNativeChatAttachmentChips, - type NativeChatPendingAttachmentChips, - type NativeChatReservedAttachment + reserveNativeChatAttachmentChips +} from './native-chat-session-attachment-drop' +import type { + NativeChatPendingAttachmentChips, + NativeChatReservedAttachment } from './native-chat-session-attachment-drop' import { releaseBrowserAttachmentFiles } from '@/lib/files/drop/browser-attachment-files' import { attachNativeChatLocalAttachmentPaths } from './native-chat-local-attachment-drop' import { useMountedRef } from '@/hooks/useMountedRef' -import { chatWorkspaceByTabId as findTerminalTabWorktreeId } from '../../../../lib/structured-chat-tab-index' +import { chatWorkspaceByTabId as findTerminalTabWorktreeId } from '../../../../lib/agent-session/tab-identity/structured-chat-tab-index' import type { CapturedNativeChatDrop } from './native-chat-pane-file-drop' export type UseNativeChatExternalAttachmentsArgs = { diff --git a/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-workspace-file-drop.ts b/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-workspace-file-drop.ts index a5c1f3ea13c..663bb35066b 100644 --- a/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-workspace-file-drop.ts +++ b/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-workspace-file-drop.ts @@ -1,5 +1,6 @@ -import { useCallback, useLayoutEffect, useRef, type DragEventHandler } from 'react' -import { useAppStore } from '@/store' +import { useCallback, useLayoutEffect, useRef } from 'react' +import type { DragEventHandler } from 'react' +import { useAppStore } from '@/store/index' import { getWorkspaceFileDragRejectionMessage, hasWorkspaceFileDragType, @@ -12,13 +13,13 @@ import { resolveNativeChatAttachmentHost } from '../uploads/native-chat-attachment-owner' import { nativeChatWorktreeNotReadyNotice } from './native-chat-attachment-notices' -import { chatWorkspaceByTabId as findTerminalTabWorktreeId } from '../../../../lib/structured-chat-tab-index' +import { chatWorkspaceByTabId as findTerminalTabWorktreeId } from '../../../../lib/agent-session/tab-identity/structured-chat-tab-index' import { parseExecutionHostId } from '../../../../../../shared/execution-host' import { nativeChatAttachmentOwnerUnchanged, - nativeChatWorkspaceAttachmentMismatchNotice, - type NativeChatResolvedPathOptions + nativeChatWorkspaceAttachmentMismatchNotice } from '../uploads/native-chat-resolved-path-ownership' +import type { NativeChatResolvedPathOptions } from '../uploads/native-chat-resolved-path-ownership' export type NativeChatResolvedPathSink = ( paths: string[], diff --git a/src/renderer/src/components/native-chat/attachments/uploads/native-chat-attachment-owner.ts b/src/renderer/src/components/native-chat/attachments/uploads/native-chat-attachment-owner.ts index bd841d66836..34c081b7412 100644 --- a/src/renderer/src/components/native-chat/attachments/uploads/native-chat-attachment-owner.ts +++ b/src/renderer/src/components/native-chat/attachments/uploads/native-chat-attachment-owner.ts @@ -1,18 +1,17 @@ -import type { AppState } from '../../../../store/types' -import { chatWorkspaceByTabId as findTerminalTabWorktreeId } from '../../../../lib/structured-chat-tab-index' - +import { chatWorkspaceByTabId as findTerminalTabWorktreeId } from '../../../../lib/agent-session/tab-identity/structured-chat-tab-index' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../../../shared/constants' import { getKnownExecutionHostIdForWorktree } from '../../../../lib/workspace/ownership/worktree-runtime-owner' import { runtimeEnvironmentIdForWorkspaceOwner } from '../../../../lib/workspace/ownership/resolve-owner' import { getConnectionIdFromState } from '../../../../lib/workspace/ownership/connection-owner-resolution' import { - type ExecutionHostId, toRuntimeExecutionHostId, getConnectionExecutionHostId, parseExecutionHostId } from '../../../../../../shared/execution-host' +import type { ExecutionHostId } from '../../../../../../shared/execution-host' import { findKnownWorktreeById } from '../../../../store/slices/worktrees/listing/detected-worktree-meta' import { getRuntimeEnvironmentRevision } from '../../../../runtime/rpc/environment-revisions/runtime-environment-revision' +import type { AppState } from '../../../../store/types' /** The paired host validates every stored attachment path when admitting a structured send. */ export type NativeChatRuntimeSessionAttachmentOwner = { diff --git a/src/renderer/src/components/native-chat/composer/controls/native-chat-composer-workspace.ts b/src/renderer/src/components/native-chat/composer/controls/native-chat-composer-workspace.ts index c0c904f9ad1..ff2855bd521 100644 --- a/src/renderer/src/components/native-chat/composer/controls/native-chat-composer-workspace.ts +++ b/src/renderer/src/components/native-chat/composer/controls/native-chat-composer-workspace.ts @@ -1,11 +1,9 @@ -import type { AppState } from '@/store/types' -import { workspaceTabs } from '@/lib/structured-chat-tab-index' +import { workspaceTabs } from '@/lib/agent-session/tab-identity/structured-chat-tab-index' import { selectExecutionHostDisplayLabel } from '@/runtime/hosts/display/execution-host-display-label' import { findIndexedRepoOwnerForHost } from '@/lib/workspace/ownership/repo-owner-index' -import { getWslDistroFromPath } from '@/lib/local-preflight-context' +import { getWslDistroFromPath } from '@/runtime/hosts/preflight/local-preflight-context' import { selectWslHostDistro } from '@/components/wsl-host-mark/WslHostMark' import { resolvePaneWslDistro } from '@/components/terminal-pane/host-state/terminal-pane-wsl-distro' -import type { Repo } from '../../../../../../shared/repo-types' import { getHostSettingOverride } from '../../../../../../shared/host-setting-overrides' import { isFolderRepo } from '../../../../../../shared/repo-kind' import { parseWorkspaceKey } from '../../../../../../shared/workspace-scope' @@ -19,9 +17,9 @@ import { import { isUnresolvedOwnerHostId, parseExecutionHostId, - toRuntimeExecutionHostId, - type ExecutionHostId + toRuntimeExecutionHostId } from '../../../../../../shared/execution-host' +import type { ExecutionHostId } from '../../../../../../shared/execution-host' import { floatingWorkspaceToWorktree, isFloatingWorkspaceId @@ -29,6 +27,8 @@ import { import { createNativeChatTabOwnerSelector } from '../../pane/ownership/native-chat-tab-owner' import { FILE_LINK_CONTEXT_INPUT_KEYS } from '../../links/actions/native-chat-file-link-context' import { resolveNativeChatTabDirectory } from '../../pane/routing/native-chat-tab-directory' +import type { AppState } from '@/store/types' +import type { Repo } from '../../../../../../shared/repo-types' import type { NativeChatStructuredComposerTransport } from '../submit/native-chat-structured-composer-transport' const OWNER_CONTEXT_INPUT_KEYS = FILE_LINK_CONTEXT_INPUT_KEYS.filter( diff --git a/src/renderer/src/components/native-chat/composer/pickers/native-chat-skill-discovery-context.ts b/src/renderer/src/components/native-chat/composer/pickers/native-chat-skill-discovery-context.ts index 5778b1b25f1..57360aa7609 100644 --- a/src/renderer/src/components/native-chat/composer/pickers/native-chat-skill-discovery-context.ts +++ b/src/renderer/src/components/native-chat/composer/pickers/native-chat-skill-discovery-context.ts @@ -1,21 +1,21 @@ -import type { AppState } from '../../../../store/types' -import type { SkillDiscoveryTarget } from '../../../../../../shared/skills' import { parseExecutionHostId } from '../../../../../../shared/execution-host' -import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target' import { getExecutionHostIdForWorktree } from '@/lib/workspace/ownership/worktree-runtime-owner' import { runtimeEnvironmentIdForWorkspaceOwner } from '@/lib/workspace/ownership/resolve-owner' -import { getLocalProjectExecutionRuntimeContext } from '@/lib/local-preflight-context' +import { getLocalProjectExecutionRuntimeContext } from '@/runtime/hosts/preflight/local-preflight-context' import { resolveWorkspaceDirectory } from '@/lib/workspace/paths/workspace-directory' import { resolveNativeChatTabDirectory, - resolveNativeChatTabDirectoryResolution, - type NativeChatTabDirectoryState + resolveNativeChatTabDirectoryResolution } from '../../pane/routing/native-chat-tab-directory' +import type { NativeChatTabDirectoryState } from '../../pane/routing/native-chat-tab-directory' import { selectDetectedWorktreesByRepo, selectFolderWorkspaces, selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' +import type { AppState } from '../../../../store/types' +import type { SkillDiscoveryTarget } from '../../../../../../shared/skills' +import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target' export type NativeChatSkillStateInputs = Pick< AppState, diff --git a/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-mention-files.ts b/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-mention-files.ts index 45c1552182c..b300a41b5aa 100644 --- a/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-mention-files.ts +++ b/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-mention-files.ts @@ -1,9 +1,9 @@ import { useMemo } from 'react' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { useRuntimeFileListForWorktree } from '@/components/quick-open-file-list' import { rankQuickOpenFilesWithHistory } from '@/components/quick-open-history-ranking' import { useQuickOpenHistory } from '@/lib/files/search/quick-open-file-history' -import { chatWorkspaceByTabId as findTerminalTabWorktreeId } from '../../../../lib/structured-chat-tab-index' +import { chatWorkspaceByTabId as findTerminalTabWorktreeId } from '../../../../lib/agent-session/tab-identity/structured-chat-tab-index' import { useFileListWorktree } from '@/store/workspaces/selection/use-selected-worktree' const MENTION_FILE_LIMIT = 20 diff --git a/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.opening-send.test.tsx b/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.opening-send.test.tsx deleted file mode 100644 index 05bc7bcf3ae..00000000000 --- a/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.opening-send.test.tsx +++ /dev/null @@ -1,416 +0,0 @@ -// @vitest-environment happy-dom -// Queued sends wait after the opening turn’s live status until actual handover, including across Stop. - -import '@testing-library/jest-dom/vitest' -import { cleanup, screen } from '@testing-library/react' -import { render } from '../../messages/actions/native-chat-tooltip-test-harness' -import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' - -// Why: these fixtures have neither inline visual owners nor sender navigation. -const unusedChatLeaves = vi.hoisted(() => ({ - inlineVisual: vi.fn(() => { - throw new Error('Unexpected inline visual in transcript fixture') - }), - openSender: vi.fn(() => { - throw new Error('Unexpected sender navigation in transcript fixture') - }) -})) -vi.mock('../../media/visuals/NativeChatInlineVisual', () => ({ - NativeChatInlineVisual: unusedChatLeaves.inlineVisual -})) -vi.mock('@/lib/open-agent-message-sender', () => ({ - openAgentMessageSender: unusedChatLeaves.openSender -})) -import { agentSessionFailureFact } from '../../../../../../shared/agent-session/failures/agent-session-failure' -import { agentSessionFailureWords } from '../../../../../../shared/agent-session/failures/agent-session-failure-words' -import { agentJournalSubmissionKey } from '../../../../../../shared/agent-session/journal/agent-session-journal-item-key' -import type { - AgentJournalItemBody, - AgentJournalRenderItem, - AgentJournalSubmission -} from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalTurnScope } from '../../../../../../shared/agent-session/journal/agent-session-journal-turn-scope' -import { - projectStructuredAgentSessionMessages, - type StructuredAgentSessionOptimisticMessage -} from '../../../../../../shared/agent-session/view/structured-agent-session-message-projection' -import { selectStructuredAgentSettledTurns } from '../../../../../../shared/agent-session/view/structured-agent-session-turn-timing' -import { NativeChatMessageList } from '../../NativeChatMessageList' -import { installNativeChatMessageListTestViewport } from '../../viewport/virtualization/native-chat-message-list-test-viewport' -import { DISPATCH_REJECTED_CANCELLED } from '../../../../../../shared/agent-session/requests/structured-agent-session-dispatch-rejection' - -describe('a message sent while the turn ahead is still opening', () => { - let restoreViewport = (): void => {} - beforeAll(() => { - restoreViewport = installNativeChatMessageListTestViewport() - }) - afterAll(() => restoreViewport()) - afterEach(cleanup) - - const THREAD: AgentJournalTurnScope = { kind: 'thread' } - const NOW = 100_000 - - function item( - itemId: string, - sequence: number, - body: AgentJournalItemBody - ): AgentJournalRenderItem { - return { itemId, revision: 0, sequence, observedAt: sequence, body, turnScope: THREAD } - } - - const userMessage = (id: string, sequence: number, text: string) => - item(agentJournalSubmissionKey(id), sequence, { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text }] - }) - - function submission( - clientMessageId: string, - overrides: Partial = {} - ): AgentJournalSubmission { - return { - clientMessageId, - fence: 1, - payloadFingerprint: clientMessageId, - dispatchState: 'pending', - providerItemId: null, - reason: null, - submittedAt: NOW, - resolvedAt: null, - handoverRecorded: true, - ...overrides - } - } - - /** A finished warm-up, then "first" handed over (row 5) with no turn record yet: its turn opens. */ - function openingFirst(): { - items: AgentJournalRenderItem[] - submissions: AgentJournalSubmission[] - } { - return { - items: [ - userMessage('warm', 1, 'warm up'), - item('turn-warm', 2, { - kind: 'turn', - turnId: 'turn-warm', - state: 'completed', - outcome: 'success', - userItemId: agentJournalSubmissionKey('warm'), - startedAt: 1_000, - completedAt: 2_000 - }), - userMessage('first', 5, 'first') - ], - submissions: [ - submission('warm', { dispatchState: 'accepted', resolvedAt: 2_000 }), - submission('first', { acceptedSequence: 3, handedOverAt: NOW }) - ] - } - } - - /** The first send's turn record, written as its turn opens; Codex names its own provider key. */ - const firstTurnOpened = (sequence: number) => - item('turn-first', sequence, { - kind: 'turn', - turnId: 'turn-first', - state: 'running', - userItemId: FIRST_TURN_PROVIDER_KEY, - startedAt: NOW - }) - const FIRST_TURN_PROVIDER_KEY = 'codex:thread:turn-first:0' - const inFirstTurn: AgentJournalTurnScope = { kind: 'turn', turnItemId: 'turn-first' } - - /** This client's own send the host has not recorded yet: its lane still runs the first handover. */ - const unrecorded = ( - clientMessageId: string, - text: string - ): StructuredAgentSessionOptimisticMessage => ({ - clientMessageId, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] }, - queuedAt: NOW + 100 - }) - - function frame( - items: AgentJournalRenderItem[], - submissions: AgentJournalSubmission[], - optimistic: StructuredAgentSessionOptimisticMessage[], - stopping = false - ): React.JSX.Element { - return ( - - ) - } - - function follows(later: HTMLElement, earlier: HTMLElement): boolean { - return Boolean(earlier.compareDocumentPosition(later) & Node.DOCUMENT_POSITION_FOLLOWING) - } - - const liveStatus = () => screen.getByText(/^Working for/) - const liveActivity = () => screen.getByText(/^(Working|Stopping)…$/) - - /** `text` is drawn after the live turn: its status and its activity line. */ - function waitsAtTheTail(text: string): void { - expect(follows(screen.getByText(text), liveStatus())).toBe(true) - expect(follows(screen.getByText(text), liveActivity())).toBe(true) - } - - // Stop withdraws B from the queue; its settled row stays after the live turn’s status and above its activity. - it('stays after the live turn when a Stop takes it back, with no frame above the live status', () => { - const { items, submissions } = openingFirst() - const view = render(frame(items, submissions, [unrecorded('b', 'B')])) - waitsAtTheTail('B') - - // Pressed: Stopping, with B now recorded and queued behind the first send. - const queued = [...items, userMessage('b', 4, 'B')] - view.rerender( - frame(queued, [...submissions, submission('b', { acceptedSequence: 4 })], [], true) - ) - waitsAtTheTail('B') - - const withdrawn = submission('b', { - acceptedSequence: 4, - dispatchState: 'rejected', - resolvedAt: NOW + 200, - ...agentSessionFailureWords(agentSessionFailureFact('cancelled'), { surface: 'rejection' }) - }) - view.rerender(frame(queued, [...submissions, withdrawn], [], true)) - const stopRow = screen.getByText('Stopped manually') - expect(follows(screen.getByText('B'), liveStatus())).toBe(true) - expect(follows(stopRow, screen.getByText('B'))).toBe(true) - expect(follows(liveActivity(), stopRow)).toBe(true) - }) - - /** Check each commit keeps second at its handover position and the live status under first. */ - function walkTurnOpening( - steps: [ - AgentJournalRenderItem[], - AgentJournalSubmission[], - StructuredAgentSessionOptimisticMessage[] - ][] - ): void { - const view = render(
) - for (const step of steps) { - view.rerender(frame(...step)) - expect(follows(liveStatus(), screen.getByText('first'))).toBe(true) - expect(follows(screen.getByText('second'), liveStatus())).toBe(true) - expect(follows(liveActivity(), screen.getByText('second'))).toBe(true) - } - } - - function turnOpening() { - const { items, submissions } = openingFirst() - const [warm, first] = submissions - if (!warm || !first) { - throw new Error('expected the warm-up and the first send') - } - const opened = [...items, firstTurnOpened(6)] - return { - submissions, - warm, - first, - opened, - // Handed over as a steer once the turn opened (row 8). - steered: [...opened, { ...userMessage('second', 8, 'second'), turnScope: inFirstTurn }], - echoed: (sent: AgentJournalSubmission): AgentJournalSubmission => ({ - ...sent, - dispatchState: 'accepted', - providerItemId: FIRST_TURN_PROVIDER_KEY, - resolvedAt: NOW + 20 - }) - } - } - - it('draws it where it lands at every step of the turn opening, even with the steer echoed first', () => { - const { submissions, warm, first, opened, steered, echoed } = turnOpening() - const handedOver = submission('second', { acceptedSequence: 7, handedOverAt: NOW + 10 }) - walkTurnOpening([ - // The turn record is in; the host has not recorded "second" yet. - [opened, submissions, [unrecorded('second', 'second')]], - // Recorded after the turn record, not yet handed over. - [ - [...opened, userMessage('second', 7, 'second')], - [...submissions, submission('second', { acceptedSequence: 7 })], - [] - ], - [steered, [...submissions, handedOver], []], - // Codex echoes the steer before the send that opened the turn, then that send. - [steered, [warm, first, echoed(handedOver)], []], - [steered, [warm, echoed(first), echoed(handedOver)], []] - ]) - }) - - // Two messages queued behind /compact, or sent while Stopping: "second" is accepted above the - // first send's handover, and the first send's turn record lands before "second" is handed over. - it('draws it where it lands at every step when it was accepted above the first send', () => { - const { submissions, warm, first, opened, steered, echoed } = turnOpening() - const [warmUp, warmTurn, firstRow, turnRecord] = opened - if (!warmUp || !warmTurn || !firstRow || !turnRecord) { - throw new Error('expected the warm-up, the first send and its turn record') - } - const queuedAbove = [warmUp, warmTurn, userMessage('second', 4, 'second'), firstRow, turnRecord] - const queued = submission('second', { acceptedSequence: 4 }) - const handedOver = { ...queued, handedOverAt: NOW + 10 } - walkTurnOpening([ - [queuedAbove, [...submissions, queued], []], - // The first send echoes while "second" is still queued. - [queuedAbove, [warm, echoed(first), queued], []], - [steered, [...submissions, handedOver], []], - [steered, [warm, first, echoed(handedOver)], []], - [steered, [warm, echoed(first), echoed(handedOver)], []] - ]) - }) -}) - -describe('a send a Stop took back before the agent started it', () => { - let restoreViewport = (): void => {} - beforeAll(() => { - restoreViewport = installNativeChatMessageListTestViewport() - }) - afterAll(() => restoreViewport()) - afterEach(cleanup) - - const STOP_ROW = 'Stopped manually' - const THREAD: AgentJournalTurnScope = { kind: 'thread' } - let sequence = 0 - - function item( - itemId: string, - body: AgentJournalItemBody, - turnScope: AgentJournalTurnScope = THREAD - ): AgentJournalRenderItem { - sequence += 1 - return { itemId, revision: 0, sequence, observedAt: sequence, body, turnScope } - } - - const sent = (id: string, text: string) => - item(agentJournalSubmissionKey(id), { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text }] - }) - - function turn( - itemId: string, - userId: string, - seconds: number, - end: { state: 'completed' | 'interrupted'; outcome: 'success' | 'cancellation' } - ) { - return item(itemId, { - kind: 'turn', - turnId: itemId, - ...end, - userItemId: agentJournalSubmissionKey(userId), - startedAt: 1_000, - completedAt: 1_000 + seconds * 1_000 - }) - } - - function warmUp(): AgentJournalRenderItem[] { - return [ - sent('warm-up', 'warm up'), - turn('t1', 'warm-up', 3, { state: 'completed', outcome: 'success' }), - item( - 't1-answer', - { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Warmed up.' }] }, - { kind: 'turn', turnItemId: 't1' } - ) - ] - } - - function submission( - clientMessageId: string, - overrides: Partial = {} - ): AgentJournalSubmission { - return { - clientMessageId, - fence: 1, - payloadFingerprint: clientMessageId, - dispatchState: 'accepted', - providerItemId: null, - reason: null, - submittedAt: 1, - resolvedAt: 2, - ...overrides - } - } - - const stopped = (id: string, overrides: Partial = {}) => - submission(id, { dispatchState: 'rejected', reason: DISPATCH_REJECTED_CANCELLED, ...overrides }) - - function journalList( - items: AgentJournalRenderItem[], - submissions: AgentJournalSubmission[], - live: { isWorking: boolean; workingStartedAt: number | null } = { - isWorking: false, - workingStartedAt: null - } - ): React.JSX.Element { - return ( - - ) - } - - function follows(later: HTMLElement, earlier: HTMLElement): boolean { - return Boolean(earlier.compareDocumentPosition(later) & Node.DOCUMENT_POSITION_FOLLOWING) - } - - it('keeps no clock it showed while the send waited on its turn', () => { - const items = [...warmUp(), sent('never-ran', 'look around')] - const { rerender } = render( - journalList( - items, - [submission('warm-up'), submission('never-ran', { dispatchState: 'pending' })], - { - isWorking: true, - workingStartedAt: Date.now() - 5_000 - } - ) - ) - expect(screen.getByText('Working for 5s')).toBeInTheDocument() - - rerender(journalList(items, [submission('warm-up'), stopped('never-ran')])) - - expect(screen.getAllByText(/^(Worked|Working) for/).map((node) => node.textContent)).toEqual([ - 'Worked for 3s' - ]) - expect(follows(screen.getByText(STOP_ROW), screen.getByText('look around'))).toBe(true) - }) -}) diff --git a/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.queued-turn-order.test.tsx b/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.queued-turn-order.test.tsx deleted file mode 100644 index ca097e112b9..00000000000 --- a/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.queued-turn-order.test.tsx +++ /dev/null @@ -1,163 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' - -import { cleanup, screen } from '@testing-library/react' -import { render } from '../../messages/actions/native-chat-tooltip-test-harness' -import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' - -// Why: these fixtures have neither inline visual owners nor sender navigation. -const unusedChatLeaves = vi.hoisted(() => ({ - inlineVisual: vi.fn(() => { - throw new Error('Unexpected inline visual in transcript fixture') - }), - openSender: vi.fn(() => { - throw new Error('Unexpected sender navigation in transcript fixture') - }) -})) -vi.mock('../../media/visuals/NativeChatInlineVisual', () => ({ - NativeChatInlineVisual: unusedChatLeaves.inlineVisual -})) -vi.mock('@/lib/open-agent-message-sender', () => ({ - openAgentMessageSender: unusedChatLeaves.openSender -})) -import type { - AgentJournalItemBody, - AgentJournalRenderItem -} from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalTurnScope } from '../../../../../../shared/agent-session/journal/agent-session-journal-turn-scope' -import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' -import type { NativeChatLiveSession } from '../../session/terminal/read/native-chat-live-session-contract' -import { NativeChatMessageList } from '../../NativeChatMessageList' -import { installNativeChatMessageListTestViewport } from '../../viewport/virtualization/native-chat-message-list-test-viewport' - -let restoreViewport = (): void => {} -beforeAll(() => { - restoreViewport = installNativeChatMessageListTestViewport() -}) -afterAll(() => restoreViewport()) -afterEach(cleanup) - -const text = ( - id: string, - role: NativeChatMessage['role'], - body: string, - timestamp: number -): NativeChatMessage => ({ - id, - role, - blocks: [{ type: 'text', text: body }], - timestamp, - source: 'transcript' -}) -const toolRun = (id: string, timestamp: number): NativeChatMessage => ({ - id, - role: 'assistant', - blocks: [{ type: 'tool-call', name: 'Bash', input: { command: 'sleep 5' }, state: 'completed' }], - timestamp, - source: 'transcript' -}) - -// The journal records B mid-turn before A’s remaining output; B’s own turn opens after A ends. -const messages = [ - text('user-a', 'user', 'Run the first job', 1), - toolRun('a-tool-1', 2), - text('user-b', 'user', 'Then run the second job', 3), - toolRun('a-tool-2', 4), - text('a-answer', 'assistant', 'FIRST DONE', 5), - text('b-answer', 'assistant', 'SECOND DONE', 6) -] - -/** With `statesScope` false the rows carry no turn scope, as a host older than turn scopes writes. */ -function journal(bState: 'running' | 'completed', statesScope: boolean): AgentJournalRenderItem[] { - const thread: AgentJournalTurnScope = { kind: 'thread' } - const inTurn = (turnItemId: string): AgentJournalTurnScope => ({ kind: 'turn', turnItemId }) - const row = ( - itemId: string, - body: AgentJournalItemBody, - turnScope: AgentJournalTurnScope, - sequence: number - ): AgentJournalRenderItem => ({ - itemId, - revision: 0, - sequence, - observedAt: sequence, - body, - ...(statesScope ? { turnScope } : {}) - }) - const said = (role: 'user' | 'assistant'): AgentJournalItemBody => ({ - kind: 'message', - role, - blocks: [] - }) - return [ - row('user-a', said('user'), thread, 1), - row( - 'turn-a', - { kind: 'turn', turnId: 'turn-a', state: 'completed', userItemId: 'user-a' }, - thread, - 2 - ), - row('a-tool-1', said('assistant'), inTurn('turn-a'), 3), - // Handed over while A runs, so the host scopes it to A's turn until its own opens. - row('user-b', said('user'), inTurn('turn-a'), 4), - row('a-tool-2', said('assistant'), inTurn('turn-a'), 5), - row('a-answer', said('assistant'), inTurn('turn-a'), 6), - row( - 'turn-b', - { kind: 'turn', turnId: 'turn-b', state: bState, userItemId: 'user-b' }, - thread, - 7 - ), - row('b-answer', said('assistant'), inTurn('turn-b'), 8) - ] -} - -const session = (status: NativeChatLiveSession['status']): NativeChatLiveSession => ({ - messages, - status, - sessionId: 'session-1', - agent: 'claude', - hasMore: false, - loadingEarlier: false, - olderHistoryGeneration: 0, - loadEarlier: vi.fn(), - readPhase: 'ready' -}) - -function expectInOrder(...nodes: Element[]): void { - for (const [index, node] of nodes.slice(1).entries()) { - expect(nodes[index]!.compareDocumentPosition(node)).toBe(Node.DOCUMENT_POSITION_FOLLOWING) - } -} - -const bar = (label: string | RegExp): Element => - screen.getByText(label).closest('[data-native-chat-turn-status]')! - -describe.each([['states each row’s turn', true]])( - 'a message the provider answered after the running turn, on a host that %s', - (_host, statesScope) => { - it("draws A's remaining rows and answer under A's bar, then B's bubble and turn", () => { - render( - - ) - - expectInOrder( - screen.getByText('Run the first job'), - bar('Worked for 17s'), - screen.getByText('FIRST DONE'), - screen.getByText('Then run the second job'), - bar(/Working for/), - screen.getByText('SECOND DONE') - ) - }) - } -) diff --git a/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.turn-membership.test.tsx b/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.turn-membership.test.tsx deleted file mode 100644 index c376839d8d6..00000000000 --- a/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.turn-membership.test.tsx +++ /dev/null @@ -1,538 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' - -import { cleanup, screen, fireEvent } from '@testing-library/react' -import { render } from '../../messages/actions/native-chat-tooltip-test-harness' - -import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' - -// Why: these fixtures have neither inline visual owners nor sender navigation. -const unusedChatLeaves = vi.hoisted(() => ({ - inlineVisual: vi.fn(() => { - throw new Error('Unexpected inline visual in transcript fixture') - }), - openSender: vi.fn(() => { - throw new Error('Unexpected sender navigation in transcript fixture') - }) -})) -vi.mock('../../media/visuals/NativeChatInlineVisual', () => ({ - NativeChatInlineVisual: unusedChatLeaves.inlineVisual -})) -vi.mock('@/lib/open-agent-message-sender', () => ({ - openAgentMessageSender: unusedChatLeaves.openSender -})) - -import { - agentJournalItemKey, - agentJournalSubmissionKey -} from '../../../../../../shared/agent-session/journal/agent-session-journal-item-key' - -import type { - AgentJournalItemBody, - AgentJournalRenderItem, - AgentJournalSubmission -} from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalTurnScope } from '../../../../../../shared/agent-session/journal/agent-session-journal-turn-scope' - -import { projectStructuredAgentSessionMessages } from '../../../../../../shared/agent-session/view/structured-agent-session-message-projection' - -import { selectStructuredAgentSettledTurns } from '../../../../../../shared/agent-session/view/structured-agent-session-turn-timing' - -import { NativeChatMessageList } from '../../NativeChatMessageList' - -import { installNativeChatMessageListTestViewport } from '../../viewport/virtualization/native-chat-message-list-test-viewport' - -import type { NativeChatLiveSession } from '../../session/terminal/read/native-chat-live-session-contract' - -import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' - -{ - const THREAD: AgentJournalTurnScope = { kind: 'thread' } - const inTurn = (turnItemId: string): AgentJournalTurnScope => ({ kind: 'turn', turnItemId }) - let sequence = 0 - - function item( - itemId: string, - body: AgentJournalItemBody, - turnScope: AgentJournalTurnScope = THREAD - ): AgentJournalRenderItem { - sequence += 1 - return { itemId, revision: 0, sequence, observedAt: sequence, body, turnScope } - } - const say = ( - itemId: string, - role: 'user' | 'assistant', - text: string, - scope: AgentJournalTurnScope = THREAD - ) => item(itemId, { kind: 'message', role, blocks: [{ type: 'text', text }] }, scope) - const work = (itemId: string, scope: AgentJournalTurnScope) => - item( - itemId, - { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'tool-call', name: 'shell', input: { command: 'ls' }, state: 'completed' }] - }, - scope - ) - const settledTurn = (itemId: string, userItemId: string, seconds: number, start: number) => - item(itemId, { - kind: 'turn', - turnId: itemId, - state: 'completed', - outcome: 'success', - userItemId, - startedAt: start, - completedAt: start + seconds * 1000 - }) - - function fruitTurn(): AgentJournalRenderItem[] { - return [ - say('u1', 'user', 'List three fruits'), - settledTurn('t1', 'u1', 4, 1_000), - say('t1-narration', 'assistant', 'Thinking about fruit.', inTurn('t1')), - work('t1-work', inTurn('t1')), - say('t1-answer', 'assistant', 'Apple, banana, cherry.', inTurn('t1')) - ] - } - - function journalList( - items: AgentJournalRenderItem[], - submissions: AgentJournalSubmission[] = [], - { - isWorking = false, - workingStartedAt = null, - hostTiming = true - }: { isWorking?: boolean; workingStartedAt?: number | null; hostTiming?: boolean } = {} - ): React.JSX.Element { - return ( - - ) - } - - function renderJournal( - items: AgentJournalRenderItem[], - submissions: AgentJournalSubmission[] = [], - isWorking = false - ): void { - render(journalList(items, submissions, { isWorking })) - } - - function follows(later: HTMLElement, earlier: HTMLElement): boolean { - return Boolean(earlier.compareDocumentPosition(later) & Node.DOCUMENT_POSITION_FOLLOWING) - } - - describe('NativeChatMessageList turns from the turn record', () => { - let restoreViewport = (): void => {} - beforeAll(() => { - restoreViewport = installNativeChatMessageListTestViewport() - }) - afterAll(() => restoreViewport()) - afterEach(cleanup) - - it('draws a message waiting behind /compact after the compaction, never above it', () => { - const compactEntry = agentJournalSubmissionKey('cmd-1') - const commandTurn = agentJournalItemKey({ - provider: 'orca', - clientMessageId: 'command-turn:cmd-1' - }) - const held = agentJournalSubmissionKey('held') - const items = [ - ...fruitTurn(), - item(compactEntry, { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: '/compact' }], - command: { name: 'compact' } - }), - settledTurn(commandTurn, compactEntry, 2, 10_000), - // Accepted while the command ran, so written before the command's result. - say(held, 'user', 'Say DONE'), - item( - 'command-result', - { kind: 'status', text: 'Conversation compacted.', presentation: 'compaction' }, - inTurn(commandTurn) - ) - ] - const submission = ( - clientMessageId: string, - handedOverAt?: number - ): AgentJournalSubmission => ({ - clientMessageId, - fence: 1, - payloadFingerprint: clientMessageId, - dispatchState: - handedOverAt === undefined && clientMessageId === 'held' ? 'pending' : 'accepted', - providerItemId: null, - reason: null, - submittedAt: 9_000, - resolvedAt: null, - handoverRecorded: true, - ...(handedOverAt !== undefined ? { handedOverAt } : {}) - }) - // The command settled; the loop has not yet handed the held message over. - renderJournal(items, [submission('cmd-1', 9_500), submission('held')]) - - expect( - follows( - screen.getByText('Say DONE'), - screen.getByRole('separator', { name: 'Context compacted' }) - ) - ).toBe(true) - }) - - it('folds a turn the provider resumed on its own under its own status', () => { - const wake = agentJournalItemKey({ - provider: 'legacy', - agent: 'claude', - sessionId: 'session-1', - recordId: 'turn-lifecycle:wake' - }) - const items = [ - ...fruitTurn(), - // Claude keys a resumed turn's record on itself: no message opened it. - settledTurn(wake, wake, 9, 20_000), - say('wake-narration', 'assistant', 'The background build finished.', inTurn(wake)), - work('wake-work', inTurn(wake)), - say('wake-answer', 'assistant', 'All tests pass now.', inTurn(wake)) - ] - renderJournal(items) - - const previousStatus = screen.getByText('Worked for 4s') - const ownStatus = screen.getByText('Worked for 9s') - expect(follows(ownStatus, screen.getByText('Apple, banana, cherry.'))).toBe(true) - expect(follows(ownStatus, previousStatus)).toBe(true) - expect(screen.queryByText('The background build finished.')).toBeNull() - expect(screen.getByText('All tests pass now.')).toBeInTheDocument() - expect(screen.getAllByRole('button', { name: 'Toggle turn details' })).toHaveLength(2) - }) - - it('clocks a turn the provider opened under its own key, not the user turn before it', () => { - const wake = 'wake' - const ask = say('u1', 'user', 'List three fruits') - const answer = (state: 'running' | 'completed') => [ - ask, - item('t1', { kind: 'turn', turnId: 't1', state, userItemId: 'u1' }), - say('t1-answer', 'assistant', 'Apple, banana, cherry.', inTurn('t1')) - ] - const local = { hostTiming: false } - const { rerender } = render( - journalList(answer('running'), [], { - ...local, - isWorking: true, - workingStartedAt: Date.now() - 7_000 - }) - ) - rerender(journalList(answer('completed'), [], local)) - expect(screen.getByText('Worked for 7s')).toBeInTheDocument() - - const woken = [ - ...answer('completed'), - item(wake, { kind: 'turn', turnId: wake, state: 'running', userItemId: 'claude:wake' }), - say('wake-answer', 'assistant', 'Checking the background build.', inTurn(wake)) - ] - rerender(journalList(woken, [], { ...local, isWorking: true, workingStartedAt: Date.now() })) - expect(screen.getByText('Worked for 7s')).toBeInTheDocument() - }) - - it('draws a message waiting behind a running /compact after its live activity', () => { - const compactEntry = agentJournalSubmissionKey('cmd-1') - const commandTurn = agentJournalItemKey({ - provider: 'orca', - clientMessageId: 'command-turn:cmd-1' - }) - const held = agentJournalSubmissionKey('held') - const items = [ - ...fruitTurn(), - item(compactEntry, { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: '/compact' }], - command: { name: 'compact' } - }), - item(commandTurn, { - kind: 'turn', - turnId: 'compact:cmd-1', - state: 'running', - userItemId: compactEntry, - startedAt: 10_000 - }), - say(held, 'user', 'Say DONE') - ] - const submission = ( - clientMessageId: string, - handedOverAt?: number - ): AgentJournalSubmission => ({ - clientMessageId, - fence: 1, - payloadFingerprint: clientMessageId, - dispatchState: handedOverAt === undefined ? 'pending' : 'accepted', - providerItemId: null, - reason: null, - submittedAt: 9_000, - resolvedAt: null, - handoverRecorded: true, - ...(handedOverAt !== undefined ? { handedOverAt } : {}) - }) - const { container } = render( - journalList(items, [submission('cmd-1', 9_500), submission('held')], { - isWorking: true, - workingStartedAt: 10_000 - }) - ) - - const activity = container.querySelector('[data-native-chat-turn-activity]') - expect(activity).not.toBeNull() - expect(follows(activity!, screen.getByText('/compact'))).toBe(true) - expect(follows(screen.getByText('Say DONE'), activity!)).toBe(true) - }) - - it("keeps a steer on its way into an ordinary running turn above that turn's activity", () => { - const steer = agentJournalSubmissionKey('steer') - const items = [ - say('u1', 'user', 'List three fruits'), - item('t1', { - kind: 'turn', - turnId: 't1', - state: 'running', - userItemId: 'u1', - startedAt: 10_000 - }), - say('t1-narration', 'assistant', 'Thinking about fruit.', inTurn('t1')), - say(steer, 'user', 'Make it four') - ] - const { container } = render( - journalList( - items, - [ - { - clientMessageId: 'steer', - fence: 1, - payloadFingerprint: 'steer', - dispatchState: 'pending', - providerItemId: null, - reason: null, - submittedAt: 10_500, - resolvedAt: null, - handoverRecorded: true - } - ], - { isWorking: true, workingStartedAt: 10_000 } - ) - ) - - const activity = container.querySelector('[data-native-chat-turn-activity]') - expect(activity).not.toBeNull() - expect(follows(activity!, screen.getByText('Make it four'))).toBe(true) - }) - }) -} - -{ - describe('NativeChatMessageList host-settled turn timing', () => { - afterEach(cleanup) - - let restoreViewport = (): void => {} - - beforeAll(() => { - restoreViewport = installNativeChatMessageListTestViewport() - }) - - afterAll(() => restoreViewport()) - - const session: NativeChatLiveSession = { - messages: [ - { - id: 'user-settled', - role: 'user', - blocks: [{ type: 'text', text: 'Settled on the host' }], - timestamp: 1, - source: 'transcript' - }, - { - id: 'assistant-settled', - role: 'assistant', - blocks: [{ type: 'text', text: 'Done.' }], - timestamp: 2, - source: 'transcript' - } - ], - status: 'ready', - sessionId: 'session-1', - agent: 'codex', - hasMore: false, - loadingEarlier: false, - olderHistoryGeneration: 0, - loadEarlier: vi.fn(), - readPhase: 'ready' - } - - it('does not render a local completed duration when the host cannot verify the end', () => { - const now = vi.spyOn(Date, 'now').mockReturnValue(1_000) - const unknownTurns = new Map([['user-settled', null]]) - try { - const { rerender } = render( - - ) - now.mockReturnValue(60_000) - rerender( - - ) - expect(screen.queryByText(/Worked for/)).not.toBeInTheDocument() - } finally { - now.mockRestore() - } - }) - }) - - describe('a thought joining a work run', () => { - let restoreViewport = (): void => {} - beforeAll(() => { - restoreViewport = installNativeChatMessageListTestViewport() - }) - afterAll(() => restoreViewport()) - afterEach(cleanup) - - const STARTED = 1_000 - - const prompt: NativeChatMessage = { - id: 'user-1', - role: 'user', - blocks: [{ type: 'text', text: 'Start the task' }], - timestamp: STARTED - 500, - source: 'transcript' - } - - const command: NativeChatMessage = { - id: 'tool-1', - role: 'assistant', - blocks: [ - { type: 'tool-call', name: 'Bash', input: { command: 'ls logs' }, state: 'completed' } - ], - timestamp: STARTED, - source: 'transcript' - } - - function reasoning(state: 'running' | 'completed'): NativeChatMessage { - return { - id: 'r-1', - role: 'reasoning', - blocks: [{ type: 'text', text: 'Weighing two approaches' }], - timestamp: STARTED + 50, - source: 'transcript', - state, - ...(state === 'completed' ? { completedAt: STARTED + 12_000 } : {}) - } - } - - function journal(rows: readonly NativeChatMessage[]): AgentJournalRenderItem[] { - return [ - { - itemId: prompt.id, - revision: 1, - sequence: 1, - observedAt: 1, - body: { kind: 'message', role: 'user', blocks: prompt.blocks } - }, - { - itemId: 'turn-1', - revision: 1, - sequence: 2, - observedAt: 2, - body: { kind: 'turn', turnId: 'turn-1', state: 'running', userItemId: prompt.id } - }, - ...rows.map((row, index) => ({ - itemId: row.id, - revision: 1, - sequence: index + 3, - observedAt: index + 3, - body: { - kind: 'message' as const, - role: row.role, - blocks: row.blocks, - ...(row.state ? { state: row.state } : {}) - } - })) - ] - } - - function list( - rows: readonly NativeChatMessage[], - props: Partial> = {} - ): React.JSX.Element { - const session: NativeChatLiveSession = { - messages: [prompt, ...rows], - status: 'working', - sessionId: 'session-1', - agent: 'claude', - hasMore: false, - loadingEarlier: false, - olderHistoryGeneration: 0, - loadEarlier: vi.fn(), - readPhase: 'ready' - } - return ( - - ) - } - - const runHeader = (): HTMLElement => - document.querySelector('[data-native-chat-tool-run-state]')! - - it('keeps a thought the reader opened live open inside its collapsed run', () => { - const { rerender } = render(list([command, reasoning('running')])) - fireEvent.click(screen.getByRole('button', { name: 'Thinking' })) - expect(screen.getByText('Weighing two approaches')).toBeInTheDocument() - - rerender(list([command, reasoning('completed')])) - expect(runHeader()).toHaveAttribute('aria-expanded', 'false') - expect(screen.queryByText('Weighing two approaches')).toBeNull() - - fireEvent.click(runHeader()) - expect(screen.getByRole('button', { name: /Thought for/ })).toHaveAttribute( - 'aria-expanded', - 'true' - ) - expect(screen.getByText('Weighing two approaches')).toBeInTheDocument() - }) - }) -} diff --git a/src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-indicator.test.tsx b/src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-indicator.test.tsx deleted file mode 100644 index 0e9617fbe84..00000000000 --- a/src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-indicator.test.tsx +++ /dev/null @@ -1,259 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' - -import { cleanup, screen } from '@testing-library/react' -import { render } from '../../messages/actions/native-chat-tooltip-test-harness' -import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' - -// Why: these fixtures have neither inline visual owners nor sender navigation. -const unusedChatLeaves = vi.hoisted(() => ({ - inlineVisual: vi.fn(() => { - throw new Error('Unexpected inline visual in transcript fixture') - }), - openSender: vi.fn(() => { - throw new Error('Unexpected sender navigation in transcript fixture') - }) -})) -vi.mock('../../media/visuals/NativeChatInlineVisual', () => ({ - NativeChatInlineVisual: unusedChatLeaves.inlineVisual -})) -vi.mock('@/lib/open-agent-message-sender', () => ({ - openAgentMessageSender: unusedChatLeaves.openSender -})) -import type { NativeChatLiveSession } from '../../session/terminal/read/native-chat-live-session-contract' -import { NativeChatMessageList } from '../../NativeChatMessageList' -import { installNativeChatMessageListTestViewport } from '../../viewport/virtualization/native-chat-message-list-test-viewport' -import type { - AgentJournalItemBody, - AgentJournalRenderItem -} from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalTurnScope } from '../../../../../../shared/agent-session/journal/agent-session-journal-turn-scope' - -let restoreViewport = (): void => {} -beforeAll(() => { - restoreViewport = installNativeChatMessageListTestViewport() -}) -afterAll(() => restoreViewport()) -afterEach(cleanup) - -const session: NativeChatLiveSession = { - messages: [ - { - id: 'assistant-1', - role: 'assistant', - blocks: [{ type: 'text', text: 'Selectable agent response.' }], - timestamp: 1, - source: 'transcript' - } - ], - status: 'ready', - sessionId: 'session-1', - agent: 'codex', - hasMore: false, - loadingEarlier: false, - olderHistoryGeneration: 0, - loadEarlier: vi.fn(), - readPhase: 'ready' -} - -// Live turns show a prompt clock and tail activity; settled turns retain the clock bar. -describe('NativeChatMessageList turn indicator', () => { - it('replaces a bridge ask row and settles it from the FIFO tool result', () => { - const user = { - id: 'bridge-user', - role: 'user' as const, - blocks: [{ type: 'text' as const, text: 'Help me choose' }], - timestamp: 1, - source: 'transcript' as const - } - const call = { - id: 'bridge-ask', - role: 'assistant' as const, - blocks: [ - { - type: 'tool-call' as const, - name: 'AskUserQuestion', - input: { questions: [{ question: 'Which branch?' }] } - } - ], - timestamp: 2, - source: 'transcript' as const - } - const bridgeSession: NativeChatLiveSession = { - ...session, - agent: 'claude', - messages: [user, call], - transcriptLifecycle: { state: 'working', turnId: user.id, timestamp: 1 } - } - const rendered = render( - - ) - - expect(screen.getByText('Awaiting user input:')).toBeInTheDocument() - expect(screen.getByText('Which branch?')).toBeInTheDocument() - expect(screen.queryByText(/AskUserQuestion/)).toBeNull() - - rendered.rerender( - - ) - - expect(screen.queryByText('Awaiting user input:')).toBeNull() - expect(screen.getByText('Asked:')).toBeInTheDocument() - expect(screen.queryByText(/AskUserQuestion/)).toBeNull() - }) - - it.each([ - ["a host that states each row's turn", true], - ['a host that states none', false] - ])( - 'keeps the live bar under the prompt that opened the running turn, not a message sent mid-turn, on %s', - (_, scoped) => { - const prompt = (id: string, text: string): NativeChatLiveSession['messages'][number] => ({ - id, - role: 'user', - blocks: [{ type: 'text', text }], - timestamp: 1, - source: 'transcript' - }) - const messages = [ - prompt('user-a', 'Run four sleeps'), - { - id: 'tool-a', - role: 'assistant' as const, - blocks: [ - { - type: 'tool-call' as const, - name: 'Bash', - input: { command: 'sleep 15' }, - state: 'running' as const - } - ], - timestamp: 2, - source: 'transcript' as const - }, - prompt('user-b', 'Also say banana') - ] - // B was handed over while A's turn runs, so a host that states scopes puts it in that turn. - const t1: AgentJournalTurnScope = { kind: 'turn', turnItemId: 't1' } - const thread: AgentJournalTurnScope = { kind: 'thread' } - const row = ( - itemId: string, - sequence: number, - body: AgentJournalItemBody, - turnScope: AgentJournalTurnScope - ): AgentJournalRenderItem => ({ - itemId, - revision: 1, - sequence, - observedAt: sequence, - body, - ...(scoped ? { turnScope } : {}) - }) - const journal = (t1State: 'running' | 'completed', t2State?: 'running' | 'completed') => [ - row('user-a', 1, { kind: 'message', role: 'user', blocks: [] }, thread), - row('t1', 2, { kind: 'turn', turnId: 't1', state: t1State, userItemId: 'user-a' }, thread), - row('tool-a', 3, { kind: 'message', role: 'assistant', blocks: [] }, t1), - row('user-b', 4, { kind: 'message', role: 'user', blocks: [] }, t1), - ...(t2State - ? [ - row( - 't2', - 5, - { kind: 'turn', turnId: 't2', state: t2State, userItemId: 'user-b' }, - thread - ) - ] - : []) - ] - const list = (props: Partial>) => ( - - ) - // B was sent while A's turn runs: the host's record still names A as the running turn's opener. - const { rerender } = render( - list({ - workingStartedAt: Date.now() - 5000, - settledTurns: new Map(), - journalItems: journal('running') - }) - ) - const barA = screen.getByText('Working for 5s').closest('[data-native-chat-turn-status]') - expect(screen.getAllByText(/Working for/)).toHaveLength(1) - expect(screen.getByText('Run four sleeps').compareDocumentPosition(barA!)).toBe( - Node.DOCUMENT_POSITION_FOLLOWING - ) - expect(barA!.compareDocumentPosition(screen.getByText('Also say banana'))).toBe( - Node.DOCUMENT_POSITION_FOLLOWING - ) - - // A’s bar settles under A; tool scope or journal order keeps A’s work inside its fold. - const expectSettledUnderA = () => { - const settledA = screen - .getByText('Worked for 17s') - .closest('[data-native-chat-turn-status]') - expect(screen.getByText('Run four sleeps').compareDocumentPosition(settledA!)).toBe( - Node.DOCUMENT_POSITION_FOLLOWING - ) - expect(settledA!.compareDocumentPosition(screen.getByText('Also say banana'))).toBe( - Node.DOCUMENT_POSITION_FOLLOWING - ) - } - - // B's own turn opens: A settles in place and B counts from A's end. - rerender( - list({ - workingStartedAt: Date.now() - 1000, - settledTurns: new Map([['user-a', { startedAt: 1, workedSeconds: 17 }]]), - journalItems: journal('completed', 'running') - }) - ) - expectSettledUnderA() - const barB = screen.getByText('Working for 1s').closest('[data-native-chat-turn-status]') - expect(screen.getByText('Also say banana').compareDocumentPosition(barB!)).toBe( - Node.DOCUMENT_POSITION_FOLLOWING - ) - - rerender( - list({ - isWorking: false, - session: { ...session, status: 'ready', messages }, - workingStartedAt: null, - settledTurns: new Map([ - ['user-a', { startedAt: 1, workedSeconds: 17 }], - ['user-b', { startedAt: 2, workedSeconds: 51 }] - ]), - journalItems: journal('completed', 'completed') - }) - ) - expectSettledUnderA() - expect( - screen - .getByText('Also say banana') - .compareDocumentPosition(screen.getByText('Worked for 51s')) - ).toBe(Node.DOCUMENT_POSITION_FOLLOWING) - expect(screen.queryByText(/Working for/)).toBeNull() - } - ) -}) diff --git a/src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-indexeddb.ts b/src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-indexeddb.ts index 41ebdcefbd2..d3575f4cee4 100644 --- a/src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-indexeddb.ts +++ b/src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-indexeddb.ts @@ -1,14 +1,14 @@ // Keep persistence thin; the draft store owns merge and lifecycle policy. -import type { - NativeChatComposerDraftStorage, - StoredNativeChatComposerDraft -} from './native-chat-composer-draft-storage' import { committedTransaction, indexedDbConnection, settledRequest -} from '@/lib/indexeddb-connection' +} from '@/app-shell/storage/indexeddb-connection' +import type { + NativeChatComposerDraftStorage, + StoredNativeChatComposerDraft +} from './native-chat-composer-draft-storage' const DATABASE_NAME = 'orca-native-chat-composer-drafts' const DATABASE_VERSION = 1 diff --git a/src/renderer/src/components/native-chat/drafts/native-chat-draft-owner.ts b/src/renderer/src/components/native-chat/drafts/native-chat-draft-owner.ts index 8cff22c0b3d..7ab37c7b842 100644 --- a/src/renderer/src/components/native-chat/drafts/native-chat-draft-owner.ts +++ b/src/renderer/src/components/native-chat/drafts/native-chat-draft-owner.ts @@ -1,5 +1,3 @@ -import type { AppState } from '../../../store/types' -import type { NativeChatComposerDraftOwner } from '@/components/native-chat/drafts/native-chat-composer-draft-storage' import { nativeChatDraftScopeTabId, structuredAgentSessionIdOfDraftScope @@ -7,8 +5,10 @@ import { import { chatWorkspaceByTabId, structuredChatWorkspacesBySessionId -} from '../../../lib/structured-chat-tab-index' +} from '../../../lib/agent-session/tab-identity/structured-chat-tab-index' import { resolveWorktreeOperationRoute } from '../../../lib/workspace/ownership/worktree-operation-route' +import type { AppState } from '../../../store/types' +import type { NativeChatComposerDraftOwner } from '@/components/native-chat/drafts/native-chat-composer-draft-storage' function workspaceOfDraftScope( state: Pick, diff --git a/src/renderer/src/components/native-chat/links/previews/native-chat-github-repo.ts b/src/renderer/src/components/native-chat/links/previews/native-chat-github-repo.ts index 29b2d4a6b10..8ae7098a1c3 100644 --- a/src/renderer/src/components/native-chat/links/previews/native-chat-github-repo.ts +++ b/src/renderer/src/components/native-chat/links/previews/native-chat-github-repo.ts @@ -1,12 +1,12 @@ import { useEffect, useMemo, useState } from 'react' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { findKnownWorktreeById } from '@/store/slices/worktrees/listing/detected-worktree-meta' -import { resolveRepoSlug } from '@/lib/repo-slug-index' +import { resolveRepoSlug } from '@/lib/workspace/catalog/repo-slug-index' import { readRepoSlugCache, REPO_SLUG_FAILURE_TTL_MS, repoSlugCacheKey -} from '@/lib/repo-slug-cache' +} from '@/lib/workspace/catalog/repo-slug-cache' import { getKnownExecutionHostIdForWorktree } from '@/lib/workspace/ownership/worktree-runtime-owner' import type { AppState } from '@/store/types' import type { WorktreeRuntimeOwnerState } from '@/lib/workspace/ownership/worktree-runtime-owner-state' diff --git a/src/renderer/src/components/native-chat/media/images/native-chat-image-runtime-context.ts b/src/renderer/src/components/native-chat/media/images/native-chat-image-runtime-context.ts index a7a017009ee..ca00c041b7d 100644 --- a/src/renderer/src/components/native-chat/media/images/native-chat-image-runtime-context.ts +++ b/src/renderer/src/components/native-chat/media/images/native-chat-image-runtime-context.ts @@ -1,17 +1,12 @@ -import { useAppStore } from '@/store' -import type { AppState } from '@/store/types' -import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' +import { useAppStore } from '@/store/index' import { runtimeTargetForOwnerEnvironment } from '@/runtime/rpc/targets/runtime-client-target' -import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target' -import { - resolveWorktreeOperationRouteResult, - type WorktreeOperationRouteResolution -} from '@/lib/workspace/ownership/worktree-operation-route' +import { resolveWorktreeOperationRouteResult } from '@/lib/workspace/ownership/worktree-operation-route' +import type { WorktreeOperationRouteResolution } from '@/lib/workspace/ownership/worktree-operation-route' import { createNativeChatTabOwnerSelector, findNativeChatTabOwnerWorktreeId } from '../../pane/ownership/native-chat-tab-owner' -import { captureDirectSshMutationExpectation } from '@/lib/ssh-mutation-expectation' +import { captureDirectSshMutationExpectation } from '@/runtime/hosts/ssh/ssh-mutation-expectation' import { parseExecutionHostId, toRuntimeExecutionHostId @@ -21,12 +16,15 @@ import { resolveNativeChatTabDirectory } from '../../pane/routing/native-chat-ta import { resolveOwner } from '@/lib/workspace/ownership/resolve-owner' import { useMemo } from 'react' import { shallow } from 'zustand/shallow' -import { firstRegisteredStructuredChatTab } from '@/lib/structured-chat-tab-index' +import { firstRegisteredStructuredChatTab } from '@/lib/agent-session/tab-identity/structured-chat-tab-index' import { selectDetectedWorktreesByRepo, selectFolderWorkspaces, selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' +import type { AppState } from '@/store/types' +import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' +import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target' /** The transcript must not read until ownership and its path are both known. */ export type NativeChatImageRuntimeContext = RuntimeFileOperationArgs | null diff --git a/src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.tsx b/src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.tsx index a8c5369ce30..edc7937b816 100644 --- a/src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.tsx +++ b/src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.tsx @@ -1,10 +1,9 @@ -import { useAppStore } from '@/store' -import { captureLinkOpenIntent } from '@/lib/link-open-intent' -import { beginLinkOpenRequest } from '@/lib/link-open-request' +import { useAppStore } from '@/store/index' +import { captureLinkOpenIntent } from '@/lib/links/placement/link-open-intent' +import { beginLinkOpenRequest } from '@/lib/links/link-open-request' import { useContext, useEffect, useRef, useState } from 'react' import { SquareArrowOutUpRight } from 'lucide-react' import { toast } from 'sonner' -import type { ArtifactWriteRequest } from '../../../../../../shared/artifacts/artifacts' import { ArtifactPublishButton } from '@/components/artifacts/ArtifactPublishButton' import { ArtifactPublishPreparationError } from '@/components/artifacts/artifact-publish-flow' import { Button } from '@/components/ui/button' @@ -20,9 +19,10 @@ import { import { NATIVE_CHAT_VISUAL_RESERVED_HEIGHT, NativeChatVisualFrame } from './NativeChatVisualFrame' import { observeTranscriptVisibility } from '../images/native-chat-image-visibility' import { NativeChatForwardedGestureContext } from '../../viewport/scroll/native-chat-reader-scroll-input' -import type { NativeChatVisualOwner } from './native-chat-visual-owner' import { readNativeChatVisual } from './native-chat-visual-read-client' import { useNativeChatVisualDocument } from './use-native-chat-visual-document' +import type { ArtifactWriteRequest } from '../../../../../../shared/artifacts/artifacts' +import type { NativeChatVisualOwner } from './native-chat-visual-owner' export function NativeChatVisualUnavailable(): React.JSX.Element { const t = useTranslate() diff --git a/src/renderer/src/components/native-chat/messages/actions/NativeChatRowActionsProvider.tsx b/src/renderer/src/components/native-chat/messages/actions/NativeChatRowActionsProvider.tsx index 831010543ca..1040d251e8c 100644 --- a/src/renderer/src/components/native-chat/messages/actions/NativeChatRowActionsProvider.tsx +++ b/src/renderer/src/components/native-chat/messages/actions/NativeChatRowActionsProvider.tsx @@ -1,6 +1,5 @@ import { useMemo } from 'react' -import { openDesktopStructuredSession } from '@/lib/activate-ai-vault-structured-session' -import type { NativeChatStructuredViewProps } from '@/components/native-chat/native-chat-view-types' +import { openDesktopStructuredSession } from '@/lib/agent-session/open/activate-ai-vault-structured-session' import { NativeChatForkContext, NativeChatForkedFromContext, @@ -8,9 +7,10 @@ import { NativeChatSideChatForkPointContext } from '@/components/native-chat/messages/actions/native-chat-fork-context' import { NativeChatRewindContext } from '@/components/native-chat/messages/actions/native-chat-rewind-context' +import { useNativeChatTabOwnerWorktreeId } from '@/components/native-chat/pane/ownership/use-native-chat-tab-owner' +import type { NativeChatStructuredViewProps } from '@/components/native-chat/native-chat-view-types' import type { NativeChatRewindSurface } from '@/components/native-chat/messages/actions/use-native-chat-rewind-host' import type { NativeChatPaneForks } from '@/components/native-chat/messages/actions/use-native-chat-fork' -import { useNativeChatTabOwnerWorktreeId } from '@/components/native-chat/pane/ownership/use-native-chat-tab-owner' /** What the pane's transcript rows offer: rewind on prompts, fork on responses, and the chat a * "Forked from" divider opens. */ diff --git a/src/renderer/src/components/native-chat/messages/agent-senders/NativeChatAgentMessageSenders.tsx b/src/renderer/src/components/native-chat/messages/agent-senders/NativeChatAgentMessageSenders.tsx index a0569defe54..1ba07b8a322 100644 --- a/src/renderer/src/components/native-chat/messages/agent-senders/NativeChatAgentMessageSenders.tsx +++ b/src/renderer/src/components/native-chat/messages/agent-senders/NativeChatAgentMessageSenders.tsx @@ -2,19 +2,19 @@ import { Fragment } from 'react' import { ArrowUpRight } from 'lucide-react' import { Button } from '@/components/ui/button' import { useTranslate } from '@/i18n/use-translate' -import { openAgentMessageSender } from '@/lib/open-agent-message-sender' -import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target' +import { openAgentMessageSender } from '@/lib/agent-session/open/open-agent-message-sender' import { useNativeChatVisualOwner } from '../../media/visuals/native-chat-visual-owner' -import { - agentMessageSendersShown, - type AgentMessageSender, - type AgentMessageSource +import { agentMessageSendersShown } from '../../../../../../shared/agent-session/agent-session-message-source' +import type { + AgentMessageSender, + AgentMessageSource } from '../../../../../../shared/agent-session/agent-session-message-source' import { unnamedSenderLabel, useAgentMessageSenderLabel } from './native-chat-agent-message-sender-label' import { useAgentMessageSenderOpens } from './native-chat-agent-message-sender-view' +import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target' /** Link a sender only where its one resolution can open something; otherwise a plain name. */ export function NativeChatAgentMessageSenders({ diff --git a/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-identity.test.tsx b/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-identity.test.tsx index 60fd7b7c5cf..366dc502a46 100644 --- a/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-identity.test.tsx +++ b/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-identity.test.tsx @@ -4,22 +4,19 @@ import { structuredAgentSessionTabId } from '../../../../../../shared/agent-session/view/structured-agent-session-projection' import '@testing-library/jest-dom/vitest' -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { cleanup, render, screen } from '@testing-library/react' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' +import { foldAgentSessionConversationNames } from '../../../../../../shared/agent-session/agent-session-conversation-names' +import type { AgentSessionConversationNames } from '../../../../../../shared/agent-session/agent-session-conversation-names' +import { testOrcaSessionId } from '../../../../../../shared/orca-session-address-test-fixture' +import { NativeChatAgentMessageSenders } from './NativeChatAgentMessageSenders' import type { AgentSessionConversationName, AgentSessionStatusSummary } from '../../../../../../shared/agent-session/agent-session-wire' -import { - foldAgentSessionConversationNames, - type AgentSessionConversationNames -} from '../../../../../../shared/agent-session/agent-session-conversation-names' import type { AgentMessageSource } from '../../../../../../shared/agent-session/agent-session-message-source' -import type { AgentStatusEntry } from '../../../../../../shared/agent-status/contracts/agent-status-types' -import { testOrcaSessionId } from '../../../../../../shared/orca-session-address-test-fixture' import type { Tab } from '../../../../../../shared/tab-types' -import { NativeChatAgentMessageSenders } from './NativeChatAgentMessageSenders' const feeds = vi.hoisted( () => @@ -63,14 +60,14 @@ vi.mock('@/runtime/native-chat/status/structured-agent-session-status-feed', () } })) const openAgentMessageSender = vi.hoisted(() => vi.fn()) -vi.mock('@/lib/open-agent-message-sender', () => ({ openAgentMessageSender })) +vi.mock('@/lib/agent-session/open/open-agent-message-sender', () => ({ openAgentMessageSender })) const ROOT = testOrcaSessionId('root-chat') const RECIPIENT = 'recipient' const SENDER = 'sender' -const PANE = 'terminal:11111111-1111-4111-8111-111111111111' +void 'terminal:11111111-1111-4111-8111-111111111111' const initial = useAppStore.getInitialState() -const providerA = { key: 'session_id' as const, id: 'provider-a' } +void { key: 'session_id' as const, id: 'provider-a' } function summary(sessionId: string): AgentSessionStatusSummary { return { @@ -131,21 +128,6 @@ function publish( listener() } } -function row(provider = providerA, agentType = 'claude'): AgentStatusEntry { - return { - paneKey: PANE, - terminalHandle: 'term-a', - worktreeId: SENDER, - state: 'working', - prompt: '', - updatedAt: 1, - stateStartedAt: 1, - stateHistory: [], - agentType, - providerSession: provider, - connectionId: null - } -} beforeEach(() => { openAgentMessageSender.mockClear() @@ -167,73 +149,6 @@ afterEach(() => { feeds.clear() }) -it('shows a chat sender by its current rename', () => { - const renamed = 'Production Release Scan & Compatibility Review' - useAppStore.setState({ unifiedTabsByWorktree: { [SENDER]: [tab(ROOT, '')] } }) - const feed = feeds.get('local')! - const status = feed.snapshot - expect(feed.names.has(ROOT)).toBe(false) - render() - expect(screen.getByText('Original sender')).toBeInTheDocument() - act(() => publish('local', undefined, [{ sessionId: ROOT, conversationName: null }])) - expect(screen.getByText('Original sender')).toBeInTheDocument() - act(() => publish('local', undefined, [{ sessionId: ROOT, conversationName: renamed }])) - const name = screen.getByText(renamed) - expect(name).toBeInTheDocument() - fireEvent.click(name) - expect(openAgentMessageSender).toHaveBeenCalledWith( - source(), - source().senders[0], - RECIPIENT, - undefined, - undefined, - renamed - ) - expect(feed.snapshot).toBe(status) - expect(status.get(ROOT)?.conversationName).toBeUndefined() -}) - -it.each([false, true])( - 'keeps CLI A saved name after provider B and a terminal rename reuse the shell (%s queued)', - (queued) => { - const terminal = { - id: 'terminal', - ptyId: 'pty', - worktreeId: SENDER, - title: 'Claude Code', - customTitle: 'Resumed A', - color: null, - sortOrder: 0, - createdAt: 0 - } - useAppStore.setState({ - agentStatusByPaneKey: { [PANE]: row() }, - tabsByWorktree: { [SENDER]: [terminal] } - }) - const from = source(true) - render() - expect(screen.getByText('Original sender')).toBeInTheDocument() - act(() => { - useAppStore.setState({ - agentStatusByPaneKey: { [PANE]: row({ key: 'session_id', id: 'provider-b' }) }, - tabsByWorktree: { [SENDER]: [{ ...terminal, customTitle: 'Renamed B' }] } - }) - }) - const link = screen.getByText('Original sender') - expect(link).toBeInTheDocument() - fireEvent.click(link) - expect(openAgentMessageSender).toHaveBeenCalledWith( - from, - from.senders[0], - RECIPIENT, - undefined, - undefined, - 'Original sender' - ) - expect(feeds.get('local')!.activations).toBe(0) - } -) - it('uses the same published /clear successor for the live sender label', () => { const live = testOrcaSessionId('22222222-2222-4222-8222-222222222222') publish('local', [summary(live)], [{ sessionId: live, conversationName: 'Continued sender' }]) diff --git a/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-label.ts b/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-label.ts index bdb35559a61..a866c94c8a2 100644 --- a/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-label.ts +++ b/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-label.ts @@ -4,13 +4,13 @@ import { } from '@/runtime/native-chat/agent-senders/agent-sender-associations' import { agentMessageSenderLabel } from '../../../../../../shared/agent-session/agent-message-presentation' import { translate } from '@/i18n/i18n' -import { useTranslate, type Translate } from '@/i18n/use-translate' +import { useTranslate } from '@/i18n/use-translate' +import type { Translate } from '@/i18n/use-translate' import { useAppStore } from '@/store/index' -import type { AppState } from '@/store/types' import { structuredChatTabBySessionId, structuredChatWorkspacesBySessionId -} from '@/lib/structured-chat-tab-index' +} from '@/lib/agent-session/tab-identity/structured-chat-tab-index' import { useStructuredConversationName } from '@/runtime/native-chat/naming/structured-conversation-name' import { structuredAgentSessionOwnerForTab, @@ -18,10 +18,11 @@ import { resolveStructuredAgentSessionOwner, executionHostIdForStructuredTarget } from '@/runtime/native-chat/session-ownership/structured-agent-session-owner' +import { getKnownExecutionHostIdForWorktree } from '@/lib/workspace/ownership/worktree-runtime-owner' +import type { AppState } from '@/store/types' import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target' import type { AgentMessageSender } from '../../../../../../shared/agent-session/agent-session-message-source' import type { Tab } from '../../../../../../shared/tab-types' -import { getKnownExecutionHostIdForWorktree } from '@/lib/workspace/ownership/worktree-runtime-owner' export function unnamedSenderLabel(t: Translate = translate): string { return t('components.native-chat.agentMessage.unnamedSender', 'an agent') diff --git a/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-open.test.tsx b/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-open.test.tsx deleted file mode 100644 index 5d2a83ba1ab..00000000000 --- a/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-open.test.tsx +++ /dev/null @@ -1,163 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup } from '@testing-library/react' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => ({ - callRuntimeRpc: vi.fn(), - activatePane: vi.fn(), - activateChat: vi.fn(async () => true), - paneUnavailable: vi.fn(), - toastInfo: vi.fn(), - focusRenderer: vi.fn(() => true), - focusRuntime: vi.fn(async () => undefined) -})) -vi.mock('@/components/terminal-pane/links/handles/terminal-handle-links', () => ({ - focusRendererTerminalHandle: mocks.focusRenderer, - focusRuntimeTerminalHandle: mocks.focusRuntime -})) -vi.mock('sonner', async (original) => ({ - ...(await original>()), - toast: { info: mocks.toastInfo, error: vi.fn() } -})) -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (original) => ({ - ...(await original>()), - callRuntimeRpc: mocks.callRuntimeRpc -})) -vi.mock('@/components/sidebar/workspace-card/activity/use-worktree-agent-activation', () => ({ - activateWorktreeAgentPane: mocks.activatePane -})) -vi.mock('@/components/terminal-pane/agent-status/stale-agent-row', async (original) => ({ - ...(await original>()), - showAgentPaneUnavailable: mocks.paneUnavailable -})) -vi.mock('@/lib/activate-ai-vault-structured-session', async (original) => ({ - ...(await original>()), - activateAiVaultStructuredSession: mocks.activateChat -})) -vi.mock('@/lib/agent-session/structured-agent-session-tab-activation', async (original) => ({ - ...(await original>()), - activateStructuredAgentSessionById: mocks.activateChat -})) - -import { useAppStore } from '@/store' - -import { openAgentMessageSender } from '@/lib/open-agent-message-sender' - -import { - agentMessageSenderOpens, - resolveAgentMessageSenderTarget -} from './native-chat-agent-message-sender-target' - -import { initialStore, resetSenderStore, status } from './native-chat-agent-sender.test-fixture' -import type { AgentSenderPublication } from '../../../../../../shared/agent-sender-associations' -import type { - AgentMessageSender, - AgentMessageSource -} from '../../../../../../shared/agent-session/agent-session-message-source' - -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../../../shared/constants' -import { handleGlobalSessionEvent } from '@/runtime/web-session-tabs-sync/global-session-events' -import { receivedAgentSenderPublications } from '@/runtime/web-session-tabs-sync/received-agent-sender-publications' -import { VisibilityResumeCoordinator } from '@/runtime/web-session-tabs-sync/visibility-resume-coordinator' -import { resetWebSessionTabsSnapshotFreshnessForTests } from '@/runtime/web-session-tabs-sync/tracking-lifecycle' - -let revision = 0 -/** Each delivery is the host's next revision, as a publishing host stamps it. */ -const publication = ( - associations: AgentSenderPublication['associations'] = [] -): AgentSenderPublication => ({ - associations, - principals: [], - attachments: [], - revision: { epoch: 'host', revision: ++revision } -}) -const terminal = (handle = 'term_0', agent: AgentMessageSender['agent'] = 'claude') => ({ - party: { address: handle, terminalHandle: handle, orcaSessionId: null }, - name: 'Worker', - agent -}) -const sourceOf = (sender: AgentMessageSender): AgentMessageSource => ({ - kind: 'agent', - senders: [sender], - orchestration: null -}) - -/** What the card draws for this sender: its avatar, and whether its name is a link. */ - -beforeEach(() => { - vi.useFakeTimers({ toFake: ['Date'] }) - vi.setSystemTime(2_000_000) - resetSenderStore() - for (const mock of Object.values(mocks)) { - mock.mockClear() - } -}) -afterEach(() => { - cleanup() - useAppStore.setState(initialStore, true) - vi.useRealTimers() -}) - -it("asks a paired host for its floating terminal's sender, which this window never mirrors", async () => { - resetWebSessionTabsSnapshotFreshnessForTests() - const paired = { kind: 'environment', environmentId: 'paired' } as const - const frame = (worktree: string, revision: number, identity: string) => { - const scope = publication([{ identity, paneKey: status(0).paneKey, worktreeId: worktree }]) - return { - type: 'updated', - worktree, - publicationEpoch: 'host', - snapshotVersion: revision, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [], - agentSenderAssociations: { ...scope, revision: { epoch: 'paired-host', revision } } - } - } - // The window's real stream receipt, as for any paired frame. - const receive = (event: ReturnType) => - act(() => - handleGlobalSessionEvent({ - environmentId: 'paired', - expectedEnvironmentConnectionGeneration: 0, - expectedTrackingGeneration: 0, - visibilityGeneration: 0, - isCurrent: () => true, - event, - response: { id: 'stream', ok: true, result: event, _meta: { runtimeId: 'rt-1' } }, - awaitingVisibilityResumeInventory: { value: false }, - coordinator: new VisibilityResumeCoordinator({ - environments: [], - environmentIdBySubscriptionSpec: [], - omissions: new Map(), - activeRuntimeWorktreeKey: () => null - }) - }) - ) - const floatingTabs = useAppStore.getState().tabsByWorktree[FLOATING_TERMINAL_WORKTREE_ID] - receive(frame(FLOATING_TERMINAL_WORKTREE_ID, 1, 'term_float')) - receive(frame('workspace', 2, 'term_0')) - const state = useAppStore.getState() - expect(Object.keys(state.agentSenderPublicationsByHost['runtime:paired'])).toEqual(['workspace']) - expect(state.tabsByWorktree[FLOATING_TERMINAL_WORKTREE_ID]).toBe(floatingTabs) - const floating = terminal('term_float') - const resolved = resolveAgentMessageSenderTarget(state, floating, 'workspace', paired, undefined) - expect(resolved).toEqual({ kind: 'gone', sender: 'terminal' }) - expect(agentMessageSenderOpens(resolved, floating)).toBe(true) - await openAgentMessageSender( - sourceOf(floating), - floating, - 'workspace', - paired, - undefined, - 'Worker' - ) - expect(mocks.callRuntimeRpc).toHaveBeenCalled() - expect(mocks.activatePane).not.toHaveBeenCalled() - // This machine's own floating terminal still publishes its senders. - const local = receivedAgentSenderPublications({}, 'local', [ - frame(FLOATING_TERMINAL_WORKTREE_ID, 3, 'term_local') - ]) - expect(Object.keys(local.local)).toEqual([FLOATING_TERMINAL_WORKTREE_ID]) -}) diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.test.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.test.tsx deleted file mode 100644 index 489be59fd78..00000000000 --- a/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.test.tsx +++ /dev/null @@ -1,201 +0,0 @@ -// @vitest-environment happy-dom -import { NativeChatHostSetupContext } from '../../host-access/native-chat-host-setup' -import '@testing-library/jest-dom/vitest' -import { cleanup, fireEvent, screen, waitFor } from '@testing-library/react' -import { render } from '../actions/native-chat-tooltip-test-harness' -import { afterEach, describe, expect, it, vi } from 'vitest' - -// Why: these fixtures have neither inline visual owners nor sender navigation. -const unusedChatLeaves = vi.hoisted(() => ({ - inlineVisual: vi.fn(() => { - throw new Error('Unexpected inline visual in transcript fixture') - }), - openSender: vi.fn(() => { - throw new Error('Unexpected sender navigation in transcript fixture') - }) -})) -vi.mock('../../media/visuals/NativeChatInlineVisual', () => ({ - NativeChatInlineVisual: unusedChatLeaves.inlineVisual -})) -vi.mock('@/lib/open-agent-message-sender', () => ({ - openAgentMessageSender: unusedChatLeaves.openSender -})) -afterEach(() => { - expect(unusedChatLeaves.inlineVisual).not.toHaveBeenCalled() - expect(unusedChatLeaves.openSender).not.toHaveBeenCalled() -}) -import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' -import { MessageRow } from './NativeChatMessageRow' -import type { NativeChatRewindSurface } from '../actions/use-native-chat-rewind-host' -import { readNativeChatQuotableSelection } from '../../selection-quotes/native-chat-quote-selection' -import type { AgentJournalSubmission } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import { agentJournalSubmissionKey } from '../../../../../../shared/agent-session/journal/agent-session-journal-item-key' -import { useStructuredAgentSessionDeliveryNotices } from '../../session/structured/delivery/use-structured-agent-session-delivery-notices' - -const confirm = vi.hoisted(() => vi.fn()) -vi.mock('@/lib/syntax-highlighting/oniguruma', async () => ({ - loadOniguruma: (await import('@/lib/syntax-highlighting/oniguruma-test-harness')) - .loadNodeOniguruma -})) -vi.mock('@/components/confirmation-dialog-context', () => ({ - useConfirmationDialog: () => confirm -})) - -afterEach(cleanup) -const signInView = { signingIn: false, signIn: vi.fn() } -const setupView = { signIn: signInView, install: null } - -function renderMessage( - role: NativeChatMessage['role'], - timestamp: number | null = 0, - rewind?: NativeChatRewindSurface -) { - return render( - - ) -} - -describe('MessageRow control visibility', () => { - it('copies an assistant reply without its visual lines, which mean nothing outside Orca', async () => { - const writeClipboardText = vi.fn().mockResolvedValue(undefined) - Object.assign(window, { api: { ui: { writeClipboardText } } }) - - render( - - ) - fireEvent.click(screen.getByRole('button', { name: 'Copy message' })) - - await waitFor(() => { - expect(writeClipboardText).toHaveBeenCalledWith('Here it is.\n\nDone.') - }) - }) -}) - -describe('which messages can be quoted', () => { - it.each([ - ['assistant', 'Message text'], - ['user', undefined], - ['system', undefined] - ] as const)('a selection in a %s message', (role, quoted) => { - const { container } = renderMessage(role) - window.getSelection()!.selectAllChildren(screen.getByText('Message text')) - - expect(readNativeChatQuotableSelection(container)?.text).toBe(quoted) - }) -}) - -describe('what a user message says about its delivery', () => { - function RecordedMessage({ submission }: { submission: AgentJournalSubmission }) { - const notices = useStructuredAgentSessionDeliveryNotices({ - pending: [], - submissions: [submission], - journalItems: [], - agentName: 'Codex', - startFailures: [] - }) - const id = agentJournalSubmissionKey(submission.clientMessageId) - return ( - - ) - } - - it('lets a user sign in from the refused message when no composer notice is shown', () => { - const { signIn } = signInView - render( - - - - ) - fireEvent.click(screen.getByRole('button', { name: 'Sign in' })) - expect(signIn).toHaveBeenCalledOnce() - }) - - it.each(['accepted', 'rejected', 'unknown'] as const)( - 'keeps a recorded steer Sending through handoff until it becomes %s', - (dispatchState) => { - const held: AgentJournalSubmission = { - clientMessageId: 'steer', - fence: 1, - payloadFingerprint: 'steer', - dispatchState: 'pending', - providerItemId: null, - reason: null, - submittedAt: 1, - resolvedAt: null, - handoverRecorded: true - } - const { rerender } = render() - expect(screen.getByText('Sending…')).toBeInTheDocument() - expect(screen.queryByRole('time')).toBeNull() - - const handedOver = { ...held, handedOverAt: 2 } - rerender() - expect(screen.getByText('Sending…')).toBeInTheDocument() - - rerender( - - ) - expect(screen.queryByText('Sending…')).toBeNull() - expect(screen.getByRole('time')).toBeInTheDocument() - if (dispatchState === 'rejected') { - expect(screen.getByText('Codex refused the message.')).toBeInTheDocument() - } - } - ) -}) diff --git a/src/renderer/src/components/native-chat/pane/actions/native-chat-header-ownership.test.tsx b/src/renderer/src/components/native-chat/pane/actions/native-chat-header-ownership.test.tsx deleted file mode 100644 index 9d967d9cec6..00000000000 --- a/src/renderer/src/components/native-chat/pane/actions/native-chat-header-ownership.test.tsx +++ /dev/null @@ -1,136 +0,0 @@ -// @vitest-environment happy-dom - -import { act, cleanup, fireEvent, render, within } from '@testing-library/react' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { TooltipProvider } from '@/components/ui/tooltip' -import { useAppStore } from '@/store' - -import type { Tab } from '../../../../../../shared/tab-types' -import { createTabsSliceMockApi } from '@/store/slices/tabs/tabs-slice-test-harness' -import { makeTabGroup } from '@/store/slices/tabs/tab-group.test-fixture' -import { - makeFolderWorkspace, - makeUnifiedTab -} from '../../../worktree-jump/worktree-jump-palette-test-fixtures' - -import * as history from '../../../right-sidebar/ai-vault/scanning/ai-vault-panel-session-list-request' -import type { NativeChatCliForkPreparation } from '@/lib/agent-session/resume/cli-fork/native-chat-cli-fork-preparation' -import type { NativeChatStructuredViewProps } from '../../native-chat-view-types' - -const mocks = vi.hoisted(() => ({ prepare: vi.fn(), launch: vi.fn(), close: vi.fn() })) -vi.mock('@/store', async () => { - const { createTestStore } = await import('@/store/testing/app-store-test-fixture') - return { useAppStore: createTestStore() } -}) -vi.mock('../../NativeChatView', async () => { - const { nativeChatPaneHeader } = await import('./NativeChatPaneHeader') - return { - default: (props: NativeChatStructuredViewProps) => ( -
- {nativeChatPaneHeader(props, 'folder:workspace', 'dark')} - {props.sessionId} -
- ) - } -}) -vi.mock('@/lib/workspace/tabs/workspace-tab-commands', () => ({ - dispatchWorkspaceTabCommand: mocks.close -})) -vi.mock('@/lib/agent-session/resume/cli-fork/native-chat-cli-fork-preparation', () => ({ - prepareNativeChatCliFork: mocks.prepare -})) -vi.mock('@/lib/launch-ai-vault-session-and-reveal', () => ({ - launchAiVaultSessionAndReveal: mocks.launch -})) -vi.mock('@/lib/agent-session/resume/history/ai-vault-session-fork-startup', () => ({ - assertAiVaultCopiedSessionLaunchAllowed: () => {}, - buildAiVaultForkStartupForWorktree: () => ({ command: 'fixture-fork' }) -})) - -import StructuredAgentSessionPaneOverlayLayer from '../routing/StructuredAgentSessionPaneOverlayLayer' - -const workspace = 'folder:workspace' -const initial = useAppStore.getInitialState() -const fullRequest = vi.spyOn(history, 'resolveAiVaultPanelSessionListRequest') - -const testWindow = window -const originalApi = window.api -const api = createTabsSliceMockApi() -vi.stubGlobal('window', testWindow) -beforeEach(() => { - vi.clearAllMocks() - Object.assign(window, { api }) - useAppStore.setState(initial, true) - useAppStore.setState({ - folderWorkspaces: [makeFolderWorkspace({ id: 'workspace', folderPath: '/repo' })] - }) -}) -afterEach(() => { - cleanup() - useAppStore.setState(initial, true) - Object.assign(window, { api: originalApi }) -}) -function seedChats(size: number) { - const tabs: Tab[] = Array.from({ length: size }, (_, index) => ({ - ...makeUnifiedTab(`chat-${index}`, workspace, `session-${index}`, `Chat ${index}`), - contentType: 'agent-session', - agentSessionAgent: 'codex', - executionHostId: 'local', - groupId: index === size - 1 ? 'second' : 'first' - })) - const groups = ['first', 'second'].map((id) => - makeTabGroup({ - id, - worktreeId: workspace, - tabOrder: tabs.filter((tab) => tab.groupId === id).map((tab) => tab.id), - activeTabId: id === 'first' ? 'chat-0' : `chat-${size - 1}` - }) - ) - useAppStore.setState({ - unifiedTabsByWorktree: { [workspace]: tabs }, - groupsByWorktree: { [workspace]: groups }, - activeGroupIdByWorktree: { [workspace]: 'first' } - }) -} -function overlay(active: boolean) { - return ( - - - - ) -} -function chat(container: HTMLElement, id: string) { - return within(container).getByText(`session-${id.slice(5)}`).parentElement! -} - -it('keeps the real Continue pending operation disabled across header hide/reveal and launches once', async () => { - seedChats(10) - const preparation = Promise.withResolvers() - mocks.prepare.mockReturnValue(preparation.promise) - mocks.launch.mockResolvedValue(undefined) - const view = render(overlay(true)) - const source = chat(view.container, 'chat-0') - const button = () => within(source).getByRole('button', { name: 'Continue with Terminal Agent' }) - expect(fullRequest).not.toHaveBeenCalled() - fireEvent.click(button()) - expect(button().hasAttribute('disabled')).toBe(true) - expect(button().getAttribute('aria-busy')).toBe('true') - view.rerender(overlay(false)) - expect(within(source).queryByRole('button')).toBeNull() - expect(useAppStore.getState().getTab('chat-0')).not.toBeNull() - view.rerender(overlay(true)) - expect(button().hasAttribute('disabled')).toBe(true) - expect(button().getAttribute('aria-busy')).toBe('true') - fireEvent.click(button()) - expect(mocks.prepare).toHaveBeenCalledTimes(1) - await act(async () => - preparation.resolve({ - copied: false, - session: { agent: 'codex', sessionId: 'fork', cwd: '/repo', codexHome: null } - }) - ) - expect(mocks.launch).toHaveBeenCalledTimes(1) - expect(button().hasAttribute('disabled')).toBe(false) - expect(button().hasAttribute('aria-busy')).toBe(false) - expect(fullRequest).toHaveBeenCalledTimes(1) -}) diff --git a/src/renderer/src/components/native-chat/pane/actions/use-native-chat-hand-off.tsx b/src/renderer/src/components/native-chat/pane/actions/use-native-chat-hand-off.tsx index f02a53bffa8..1fbf651df4a 100644 --- a/src/renderer/src/components/native-chat/pane/actions/use-native-chat-hand-off.tsx +++ b/src/renderer/src/components/native-chat/pane/actions/use-native-chat-hand-off.tsx @@ -1,24 +1,23 @@ import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import { withTimeout } from '../../../../../../shared/promise-timeout-fallback' -import { useCallback, useLayoutEffect, useRef, useState, type ReactNode } from 'react' -import { useAppStore } from '@/store' -import { structuredChatTabById } from '@/lib/structured-chat-tab-index' +import { useCallback, useLayoutEffect, useRef, useState } from 'react' +import type { ReactNode } from 'react' +import { useAppStore } from '@/store/index' +import { structuredChatTabById } from '@/lib/agent-session/tab-identity/structured-chat-tab-index' import { useStructuredChatTabConversationName } from '@/runtime/native-chat/naming/structured-conversation-name' import { AgentSessionContinuationDialog } from '@/components/agent-session-continuation/AgentSessionContinuationDialog' -import { - buildAgentSessionContinuationPrompt, - type AgentSessionContinuationRequest -} from '@/lib/agent-session/context/agent-session-continuation' +import { buildAgentSessionContinuationPrompt } from '@/lib/agent-session/context/agent-session-continuation' +import type { AgentSessionContinuationRequest } from '@/lib/agent-session/context/agent-session-continuation' import { isTuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent-config' import { callStructuredAgentSession } from '@/runtime/native-chat/requests/structured-agent-session-call' import { supportsStructuredAgentSessionContinuationContext } from '@/runtime/native-chat/host-capabilities/structured-agent-session-host-support' -import type { AgentSessionContinuationContext } from '../../../../../../shared/agent-session/agent-session-wire' import { executionHostIdForStructuredTarget } from '@/runtime/native-chat/session-ownership/structured-agent-session-owner' +import { buildAgentSessionHandoffContext } from '../../../../../../shared/agent-session-handoff-context' +import type { AgentSessionContinuationContext } from '../../../../../../shared/agent-session/agent-session-wire' import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' import type { NativeChatStructuredViewProps } from '../../native-chat-view-types' import type { NativeChatFileLinkContext } from '../../links/actions/native-chat-file-link-context' -import { buildAgentSessionHandoffContext } from '../../../../../../shared/agent-session-handoff-context' export type NativeChatHandOff = { /** This chat can seed another agent from its owning workspace. */ diff --git a/src/renderer/src/components/native-chat/pane/actions/use-native-chat-quick-commands-menu.tsx b/src/renderer/src/components/native-chat/pane/actions/use-native-chat-quick-commands-menu.tsx index 5fb7a2c6a59..e7293a7252f 100644 --- a/src/renderer/src/components/native-chat/pane/actions/use-native-chat-quick-commands-menu.tsx +++ b/src/renderer/src/components/native-chat/pane/actions/use-native-chat-quick-commands-menu.tsx @@ -1,13 +1,13 @@ import { useEffect, useState } from 'react' import { useTerminalQuickCommandHosts } from '@/hooks/use-terminal-quick-command-hosts' import { useVisibleTerminalQuickCommandHosts } from '@/hooks/use-visible-terminal-quick-command-hosts' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { getIndexedReposById } from '@/store/repos/repository-catalog-index' import { getRepoIdFromWorktreeId } from '../../../../../../shared/worktree/id' import type { ExecutionHostId } from '../../../../../../shared/execution-host' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../../../shared/constants' import type { TerminalQuickCommand } from '../../../../../../shared/terminal/quick-commands/terminal-quick-command-types' -import { runQuickCommandInNewTab } from '@/lib/run-quick-command-in-new-tab' +import { runQuickCommandInNewTab } from '@/lib/terminal/quick-commands/run-quick-command-in-new-tab' import { TerminalQuickCommandsSubmenu } from '../../../terminal-pane/quick-commands/TerminalQuickCommandsSubmenu' import { TerminalQuickCommandEditorDialog } from '../../../terminal-pane/quick-commands/TerminalQuickCommandEditorDialog' import { createTerminalQuickCommandDraft } from '../../../terminal-quick-commands/TerminalQuickCommandDialog' diff --git a/src/renderer/src/components/native-chat/pane/ownership/native-chat-runtime-owner.ts b/src/renderer/src/components/native-chat/pane/ownership/native-chat-runtime-owner.ts index f252d3cdf55..a0761434ace 100644 --- a/src/renderer/src/components/native-chat/pane/ownership/native-chat-runtime-owner.ts +++ b/src/renderer/src/components/native-chat/pane/ownership/native-chat-runtime-owner.ts @@ -1,8 +1,8 @@ import { runtimeEnvironmentIdOrLocalUnlessTwin } from '@/lib/workspace/ownership/worktree-runtime-owner' +import { createNativeChatTabOwnerSelector } from './native-chat-tab-owner' +import { chatWorkspaceByTabId as findTerminalTabWorktreeId } from '../../../../lib/agent-session/tab-identity/structured-chat-tab-index' import type { WorktreeRuntimeOwnerState } from '@/lib/workspace/ownership/worktree-runtime-owner-state' import type { AppState } from '@/store/types' -import { createNativeChatTabOwnerSelector } from './native-chat-tab-owner' -import { chatWorkspaceByTabId as findTerminalTabWorktreeId } from '../../../../lib/structured-chat-tab-index' export type NativeChatRuntimeOwnerState = Pick & WorktreeRuntimeOwnerState diff --git a/src/renderer/src/components/native-chat/pane/ownership/native-chat-tab-owner.ts b/src/renderer/src/components/native-chat/pane/ownership/native-chat-tab-owner.ts index 9885da1fa04..d7924c868bf 100644 --- a/src/renderer/src/components/native-chat/pane/ownership/native-chat-tab-owner.ts +++ b/src/renderer/src/components/native-chat/pane/ownership/native-chat-tab-owner.ts @@ -1,7 +1,7 @@ import { chatWorkspaceByTabId, chatWorkspaceByTabId as findTerminalTabWorktreeId -} from '../../../../lib/structured-chat-tab-index' +} from '../../../../lib/agent-session/tab-identity/structured-chat-tab-index' import type { AppState } from '../../../../store/types' type NativeChatTabOwnerState = Pick & { diff --git a/src/renderer/src/components/native-chat/pane/routing/StructuredAgentSessionPaneOverlayLayer.tsx b/src/renderer/src/components/native-chat/pane/routing/StructuredAgentSessionPaneOverlayLayer.tsx index 45369165f09..8072d12b811 100644 --- a/src/renderer/src/components/native-chat/pane/routing/StructuredAgentSessionPaneOverlayLayer.tsx +++ b/src/renderer/src/components/native-chat/pane/routing/StructuredAgentSessionPaneOverlayLayer.tsx @@ -2,7 +2,7 @@ import { memo, useCallback, useMemo } from 'react' import { useShallow } from 'zustand/react/shallow' import type { Tab, TabGroup } from '../../../../../../shared/tab-types' import { useAppStore } from '@/store' -import { useThemeBackgroundStore } from '@/store/appearance/theme-background' +import { useWindowBackdropActive } from '@/app-shell/appearance/window-backdrop' import { structuredAgentSessionOwnerForTab, structuredAgentSessionTargetForHost @@ -37,7 +37,7 @@ const StructuredAgentSessionOverlaySlot = memo(function StructuredAgentSessionOv // Resolve from the tab’s recorded host because workspace ids can collide across hosts. const owner = useAppStore((state) => structuredAgentSessionOwnerForTab(state, tab)) const target = useMemo(() => structuredAgentSessionTargetForHost(owner), [owner]) - const themeBackgroundActive = useThemeBackgroundStore((state) => state.active) + const backdropActive = useWindowBackdropActive() if (!target) { return null } @@ -45,8 +45,8 @@ const StructuredAgentSessionOverlaySlot = memo(function StructuredAgentSessionOv diff --git a/src/renderer/src/components/native-chat/pane/routing/native-chat-tab-directory.ts b/src/renderer/src/components/native-chat/pane/routing/native-chat-tab-directory.ts index 10e18a26d0d..53d45011d08 100644 --- a/src/renderer/src/components/native-chat/pane/routing/native-chat-tab-directory.ts +++ b/src/renderer/src/components/native-chat/pane/routing/native-chat-tab-directory.ts @@ -1,11 +1,9 @@ -import type { ExecutionHostId } from '../../../../../../shared/execution-host' import { isFloatingWorkspaceId } from '../../../../../../shared/floating-workspace-worktree' -import { - resolveWorkspaceDirectory, - type WorkspaceDirectoryState -} from '@/lib/workspace/paths/workspace-directory' +import { resolveWorkspaceDirectory } from '@/lib/workspace/paths/workspace-directory' +import type { WorkspaceDirectoryState } from '@/lib/workspace/paths/workspace-directory' +import { firstRegisteredStructuredChatTab } from '@/lib/agent-session/tab-identity/structured-chat-tab-index' +import type { ExecutionHostId } from '../../../../../../shared/execution-host' import type { StructuredSessionLaunchDirectory } from '@/store/slices/agent-status/structured-session-launch-directories' -import { firstRegisteredStructuredChatTab } from '@/lib/structured-chat-tab-index' type NativeChatDirectoryTab = { id: string diff --git a/src/renderer/src/components/native-chat/pane/routing/use-native-chat-toggle-shortcut.ts b/src/renderer/src/components/native-chat/pane/routing/use-native-chat-toggle-shortcut.ts index 352c3e4a35b..bdb25e0d802 100644 --- a/src/renderer/src/components/native-chat/pane/routing/use-native-chat-toggle-shortcut.ts +++ b/src/renderer/src/components/native-chat/pane/routing/use-native-chat-toggle-shortcut.ts @@ -4,7 +4,7 @@ import { matchesRecentTabSwitcherChord } from '../../../../../../shared/window-s import { globalShortcutTargetYields, findPluginCommandForKeybinding -} from '@/lib/plugin-command-keybindings' +} from '@/lib/plugins/commands/plugin-command-keybindings' import { getKeybindingContext } from '../../../terminal-workspace-model' import { ModifierDoubleTapDetector, diff --git a/src/renderer/src/components/native-chat/queue/NativeChatQueuedMessageList.in-flight.test.tsx b/src/renderer/src/components/native-chat/queue/NativeChatQueuedMessageList.in-flight.test.tsx deleted file mode 100644 index 60699c4da8d..00000000000 --- a/src/renderer/src/components/native-chat/queue/NativeChatQueuedMessageList.in-flight.test.tsx +++ /dev/null @@ -1,96 +0,0 @@ -// @vitest-environment happy-dom - -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' - -vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) -// A card's sender line opens and names agents through modules this test does not exercise. -vi.mock('@/lib/open-agent-message-sender', () => ({ openAgentMessageSender: vi.fn() })) -vi.mock('@/runtime/native-chat/naming/structured-conversation-name', () => ({ - useStructuredChatTabConversationName: () => null -})) -vi.mock('../../../store/index', () => { - const state = { updateSettings: vi.fn() } - const useAppStore = (selector: (value: typeof state) => unknown): unknown => selector(state) - useAppStore.getState = () => state - return { useAppStore } -}) - -import { toast } from 'sonner' -import { TooltipProvider } from '@/components/ui/tooltip' -import { NativeChatQueuedMessageList } from './NativeChatQueuedMessageList' -import { useStructuredAgentSessionQueuedMessages } from './use-structured-agent-session-queued-messages' -import type { StructuredAgentSessionWrite } from '../session/structured/writes/use-structured-agent-session-mutate' -import type { AgentSessionQueuedMessage } from '../../../../../shared/agent-session/requests/agent-session-queued-message-wire' - -function waitingDraft(messageId: string, position: number): AgentSessionQueuedMessage { - return { - messageId, - position, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: `${messageId} text` }] }, - state: 'waiting' - } -} - -/** The list over the real controller, held after a Stop, deleting through `write`. */ -function renderHeldQueue( - queuedMessages: AgentSessionQueuedMessage[], - write: StructuredAgentSessionWrite, - mutate = vi.fn(async (..._call: [string, string, Record]) => null) -): void { - function HeldQueue(): React.JSX.Element { - const owner = useStructuredAgentSessionQueuedMessages({ - admit: () => ({ target: { kind: 'local' }, write: write, mutate: async () => null }), - capturePresentation: () => () => true, - enabled: true, - queuedMessages, - queuePause: { reason: 'stopped' }, - submissions: [], - hasPendingPrompt: false, - isWorking: false, - composerScopeKey: undefined, - mutate: mutate, - editTransport: { target: { kind: 'local' }, sessionId: 'session', capable: false, write } - }) - return - } - render( - - - - ) -} - -afterEach(cleanup) - -it('a slow Clear all greys Clear all, Resume and every card until the host answers', async () => { - vi.mocked(toast.error).mockClear() - const answer = Promise.withResolvers() - const write = vi.fn(async () => { - await answer.promise - return { - kind: 'not-done' as const, - notice: 'Could not delete', - failure: { kind: 'failed' as const } - } - }) - renderHeldQueue([waitingDraft('a', 1), waitingDraft('b', 2)], write) - const clearAll = () => screen.getByRole('button', { name: 'Clear all' }) - const controls = () => [ - clearAll(), - screen.getByRole('button', { name: 'Resume' }), - ...screen.getAllByRole('button', { name: /^(Delete|Steer|Send|More actions)$/ }) - ] - fireEvent.click(clearAll()) - fireEvent.click(clearAll()) - await waitFor(() => - controls().forEach((control) => expect(control).toHaveProperty('disabled', true)) - ) - expect(write).toHaveBeenCalledTimes(2) - answer.resolve() - await waitFor(() => - controls().forEach((control) => expect(control).toHaveProperty('disabled', false)) - ) - expect(screen.getAllByRole('listitem')).toHaveLength(2) - expect(toast.error).toHaveBeenCalledExactlyOnceWith('Could not delete') -}) diff --git a/src/renderer/src/components/native-chat/session/attention/structured-attention-dispatch.test.ts b/src/renderer/src/components/native-chat/session/attention/structured-attention-dispatch.test.ts index e1a53893a12..481dcb61945 100644 --- a/src/renderer/src/components/native-chat/session/attention/structured-attention-dispatch.test.ts +++ b/src/renderer/src/components/native-chat/session/attention/structured-attention-dispatch.test.ts @@ -18,11 +18,11 @@ import { isStructuredTab } from '../../../../../../shared/agent-session/view/str beforeEach(() => setPresenceGated(false)) afterEach(() => setPresenceGated(true)) -vi.mock('@/store', () => ({ useAppStore: { getState: () => store.getState() } })) -vi.mock('@/lib/desktop-notification-sound', () => ({ +vi.mock('@/store/index', () => ({ useAppStore: { getState: () => store.getState() } })) +vi.mock('@/lib/notifications/desktop-notification-sound', () => ({ playDesktopNotificationSound: vi.fn(async () => false) })) -vi.mock('@/lib/blocked-notification-fallback', () => ({ +vi.mock('@/lib/notifications/blocked-notification-fallback', () => ({ showBlockedNotificationFallbackToast: vi.fn() })) diff --git a/src/renderer/src/components/native-chat/session/options/catalog/native-chat-session-option-discovery.ts b/src/renderer/src/components/native-chat/session/options/catalog/native-chat-session-option-discovery.ts index 82083821e4e..20433893bb7 100644 --- a/src/renderer/src/components/native-chat/session/options/catalog/native-chat-session-option-discovery.ts +++ b/src/renderer/src/components/native-chat/session/options/catalog/native-chat-session-option-discovery.ts @@ -1,6 +1,4 @@ -import type { AgentType } from '../../../../../../../shared/agent-status/contracts/agent-status-types' import { createClaudeCatalogOptions } from '../../../../../../../shared/agent-session/options/agent-session-option-catalog-claude-codex' -import type { CatalogModel } from '../../../../../../../shared/agent-session/options/agent-session-option-catalog-types' import { catalogModelsFromModelDiscovery } from '../../../../../../../shared/native-chat/input/native-chat-discovered-catalog-models' import { getCommitMessageModelDiscoveryHostKeyForLocalRuntime, @@ -13,19 +11,19 @@ import { getConnectionIdFromState } from '@/lib/workspace/ownership/connection-o import { getLocalProjectExecutionRuntimeContext, getWslDistroFromPath -} from '@/lib/local-preflight-context' +} from '@/runtime/hosts/preflight/local-preflight-context' import { discoverRuntimeCommitMessageModels } from '@/runtime/source-control/git/runtime-git-generation-client' -import { - getRuntimeGitScope, - type RuntimeGitContext -} from '@/runtime/source-control/git/runtime-git-client-context' +import { getRuntimeGitScope } from '@/runtime/source-control/git/runtime-git-client-context' +import type { RuntimeGitContext } from '@/runtime/source-control/git/runtime-git-client-context' import { callStructuredAgentSession } from '@/runtime/native-chat/requests/structured-agent-session-call' +import { useAppStore } from '@/store/index' +import { selectFileListWorktree } from '@/store/workspaces/selection/known-worktree-selection' +import type { AgentType } from '../../../../../../../shared/agent-status/contracts/agent-status-types' +import type { CatalogModel } from '../../../../../../../shared/agent-session/options/agent-session-option-catalog-types' import type { AgentSessionModelCatalogResult, AgentSessionModelOption } from '../../../../../../../shared/agent-session/agent-session-wire' -import { useAppStore } from '@/store/index' -import { selectFileListWorktree } from '@/store/workspaces/selection/known-worktree-selection' export type NativeChatModelDiscoveryContext = { hostKey: string diff --git a/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-bridge-failed-start.test.tsx b/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-bridge-failed-start.test.tsx deleted file mode 100644 index 99f419e3b7a..00000000000 --- a/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-bridge-failed-start.test.tsx +++ /dev/null @@ -1,408 +0,0 @@ -// @vitest-environment happy-dom - -// Refused creates publish no host session; bridge launch failures into tab/workspace rows until retry or closure. - -import type * as LaunchErrors from '@/lib/agent-session/launch/structured-agent-session-launch-errors' -import { act, cleanup, render, waitFor } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest' -import type { - AgentSessionHistoryResult, - AgentSessionMutationResult, - AgentSessionSendResult, - AgentSessionStatusEvent -} from '../../../../../../shared/agent-session/agent-session-wire' - -import type { AgentStatusEntry } from '../../../../../../shared/agent-status/contracts/agent-status-types' -import { structuredAgentSessionPaneKey } from '../../../../../../shared/agent-session/view/structured-agent-session-projection' -import type { Tab } from '../../../../../../shared/tab-types' -import type { StructuredAgentSessionLaunchIntent } from '@/lib/launch-structured-agent-session' -import type { AppState } from '@/store/types' - -type TestStore = { - getState: () => AppState - setState: (state: Partial & { testRuntimeOwner?: string | null }) => void -} - -const mocks = vi.hoisted(() => { - const hoisted: { - store: TestStore | null - call: Mock - history: Mock - subscribeStatus: Mock - unsubscribe: Mock - createIntent: Mock - retryIntent: Mock - restoreIntent: Mock - launch: Mock - } = { - store: null, - call: vi.fn(), - history: vi.fn(), - subscribeStatus: vi.fn(), - unsubscribe: vi.fn(), - createIntent: vi.fn(), - retryIntent: vi.fn(), - restoreIntent: vi.fn(), - launch: vi.fn() - } - return hoisted -}) - -import { useAppStore } from '@/store' -mocks.store = useAppStore - -vi.mock('sonner', () => ({ toast: { error: vi.fn(), message: vi.fn() } })) - -vi.mock('@/lib/workspace/ownership/worktree-runtime-owner', () => ({ - getExecutionHostIdForWorktree: () => 'local' -})) - -vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-call', () => ({ - callStructuredAgentSession: mocks.call -})) - -vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ - subscribeStructuredAgentSession: vi.fn(), - subscribeStructuredAgentSessionStatus: mocks.subscribeStatus -})) - -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ - callRuntimeRpc: mocks.history -})) -vi.mock('@/runtime/rpc/compatibility/runtime-compatibility-probe', () => ({ - ensureRuntimeEnvironmentCompatible: async () => {} -})) - -vi.mock('@/runtime/local-structured-session-tabs-sync/inventory-refresh', () => ({ - refreshLocalStructuredSessionTabs: vi.fn(async () => []) -})) - -const launchErrorMocks = vi.hoisted(() => { - class StructuredAgentSessionCreateRefusalError extends Error {} - return { StructuredAgentSessionCreateRefusalError } -}) - -vi.mock('@/lib/agent-session/launch/structured-agent-session-launch-errors', async () => ({ - ...(await vi.importActual( - '@/lib/agent-session/launch/structured-agent-session-launch-errors' - )), - ...launchErrorMocks -})) - -vi.mock('@/lib/agent-session/launch/structured-agent-session-launch-create-call', () => ({ - launchStructuredAgentSession: mocks.launch -})) - -vi.mock('@/lib/launch-structured-agent-session', () => { - return { - createStructuredAgentSessionLaunchIntent: mocks.createIntent, - retryStructuredAgentSessionLaunchIntent: mocks.retryIntent, - restoreStructuredAgentSessionLaunchIntent: mocks.restoreIntent, - abandonStructuredAgentSessionLaunchIntent: vi.fn(), - launchStructuredAgentSession: mocks.launch, - StructuredAgentSessionCreateRefusalError: - launchErrorMocks.StructuredAgentSessionCreateRefusalError - } -}) - -import { useRunningTerminalCloseConfirmStore } from '@/store/slices/tabs/closing/running-terminal-close-confirm' -import { StructuredAgentSessionStatusBridge } from './StructuredAgentSessionStatusBridge' -import { StructuredAgentSessionCreateRefusalError } from '@/lib/agent-session/launch/structured-agent-session-launch-errors' -import { - retryStructuredAgentSessionLaunch, - startStructuredAgentLaunch -} from '@/lib/agent-session/launch/structured-agent-session-launch' -import { resetStructuredAgentLaunchRegistryForTests } from '@/lib/agent-session/launch/structured-agent-session-launch-registry' -import { resetStructuredAgentLaunchPersistenceForTests } from '@/lib/agent-session/launch/structured-agent-session-launch-persistence' -import { resetStructuredAgentSessionStatusFeedsForTests } from '@/runtime/native-chat/status/structured-agent-session-status-feed' -import { - resetTerminalTabActivityFlagsCacheForTest, - resolveTerminalTabActivityStatus -} from '../../../tab-bar/terminal-tab-activity-status' - -import { countActivityUnread } from '../../../activity/useActivityUnreadCount' - -import { getDefaultSettings } from '../../../../../../shared/constants' -import { - sendStructuredAgentSessionMessage, - resetStructuredAgentSessionSendsForTests -} from '../structured/delivery/structured-agent-session-message-sender' -import { noteStructuredAgentSessionFence } from '../structured/delivery/structured-agent-session-send-attempt' - -async function closeChat(skipRunningProcessConfirm = false): Promise { - const { createWorkspaceTabCloseCommands } = - await import('../../../tab-group/workspace-tab-close-commands') - createWorkspaceTabCloseCommands({ - worktreeId: WORKTREE_ID, - groupTabs: [structuredTab] - }).closeItem(structuredTab.id, { skipRunningProcessConfirm }) -} - -const WORKTREE_ID = 'wt-1' -const SESSION_ID = 'session-1' -const TAB_CREATED_AT = 1_000 -const FAILED_AT = 10 * 60 * 60_000 -const PANE_KEY = structuredAgentSessionPaneKey(`structured-agent-session-${SESSION_ID}`, SESSION_ID) - -const structuredTab = { - id: `structured-agent-session-${SESSION_ID}`, - worktreeId: WORKTREE_ID, - groupId: 'group-1', - contentType: 'agent-session', - entityId: SESSION_ID, - label: 'Claude Chat', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: TAB_CREATED_AT, - isPinned: false, - agentSessionAgent: 'claude', - executionHostId: 'local' -} satisfies Tab - -const intent: StructuredAgentSessionLaunchIntent = { - worktreeId: WORKTREE_ID, - sessionId: SESSION_ID, - executionHostId: 'local', - target: { kind: 'local' }, - agent: 'claude', - params: { - envelope: { - sessionId: SESSION_ID, - clientOperationId: 'operation-1', - expectedRuntimeFence: null, - payloadFingerprint: 'fingerprint-1' - }, - worktree: `id:${WORKTREE_ID}`, - agent: 'claude' - } -} - -function store(): TestStore { - if (!mocks.store) { - throw new Error('store missing') - } - return mocks.store -} - -function rows(): AgentStatusEntry[] { - return Object.values(store().getState().agentStatusByPaneKey) -} - -function tabStatus(): string { - const state = store().getState() - return resolveTerminalTabActivityStatus({ - tab: { id: structuredTab.id, title: structuredTab.label, launchAgent: 'claude' }, - agentStatusByPaneKey: state.agentStatusByPaneKey, - agentStatusEpoch: state.agentStatusEpoch - }) -} - -async function flush(): Promise { - for (let i = 0; i < 20; i += 1) { - await act(async () => { - await Promise.resolve() - }) - } -} - -async function connect(): Promise<(event: AgentSessionStatusEvent) => void> { - render() - await waitFor(() => expect(mocks.subscribeStatus).toHaveBeenCalledOnce()) - const emit: (event: AgentSessionStatusEvent) => void = mocks.subscribeStatus.mock.calls[0]?.[1] - // The host never created the session, so it publishes nothing for it. - act(() => emit({ type: 'snapshot', sessions: [] })) - return (event) => act(() => emit(event)) -} - -/** Preserve saved launches/acknowledgments across restart; drop live rows and launch memory. */ -async function restart(): Promise { - const { acknowledgedAgentsByPaneKey } = store().getState() - cleanup() - store().setState({ agentStatusByPaneKey: {}, acknowledgedAgentsByPaneKey }) - resetStructuredAgentLaunchRegistryForTests() - resetStructuredAgentLaunchPersistenceForTests() - resetStructuredAgentSessionStatusFeedsForTests() - resetTerminalTabActivityFlagsCacheForTest() - mocks.subscribeStatus.mockClear() - await connect() -} - -function setClock(now: number): void { - vi.spyOn(Date, 'now').mockReturnValue(now) -} - -function acknowledge(at: number): void { - store().setState({ acknowledgedAgentsByPaneKey: { [PANE_KEY]: at } }) -} - -function unread(): number { - return countActivityUnread(store().getState()) -} - -let failedStarts = 0 - -async function failStart(): Promise { - mocks.createIntent.mockReturnValueOnce(intent) - mocks.launch.mockRejectedValueOnce(new StructuredAgentSessionCreateRefusalError('refused')) - failedStarts += 1 - const launch = startStructuredAgentLaunch(WORKTREE_ID, 'claude', { - requestId: `request-${failedStarts}` - }) - await expect(launch.launchResult).rejects.toBeInstanceOf(StructuredAgentSessionCreateRefusalError) - await flush() -} - -const completeIdle: AgentSessionHistoryResult = { - ok: true, - page: { - sessionId: SESSION_ID, - epoch: 'e', - direction: 'tail', - items: [], - removedItemIds: [], - submissions: [], - window: { oldest: null, newest: null, nextCursor: { epoch: 'e', sequence: 1 } }, - hasOlder: false, - hasNewer: false, - latestTurn: null, - working: false, - actionablePromptIds: [], - backgroundTasks: null, - nextQueuedMessageId: null - } -} -const pendingClose = () => - useRunningTerminalCloseConfirmStore.getState().runningTerminalCloseConfirm -async function ready(mode = 'idle'): Promise { - const emit = await connect() - emit({ - type: 'status', - session: { - sessionId: SESSION_ID, - workspaceId: WORKTREE_ID, - agent: 'claude', - status: mode === 'idle' ? 'idle' : 'working', - latestPrompt: '', - updatedAt: 1 - } - }) - store().setState({ - settings: - mode === 'null settings' - ? null - : { - ...getDefaultSettings('/tmp/pr-34236'), - skipCloseTerminalWithRunningProcessConfirm: mode === 'opt-out' - } - }) - mocks.history.mockReset().mockResolvedValue(completeIdle) -} - -describe('a chat whose start failed', () => { - beforeEach(() => { - vi.clearAllMocks() - localStorage.clear() - resetStructuredAgentLaunchRegistryForTests() - resetStructuredAgentLaunchPersistenceForTests() - resetStructuredAgentSessionStatusFeedsForTests() - resetTerminalTabActivityFlagsCacheForTest() - mocks.subscribeStatus.mockResolvedValue({ unsubscribe: mocks.unsubscribe }) - mocks.retryIntent.mockImplementation((prior: StructuredAgentSessionLaunchIntent) => prior) - mocks.restoreIntent.mockReturnValue(intent) - store().setState({ - agentStatusByPaneKey: {}, - acknowledgedAgentsByPaneKey: {}, - retainedAgentsByPaneKey: {}, - unifiedTabsByWorktree: { [WORKTREE_ID]: [structuredTab] } - }) - }) - - afterEach(() => { - cleanup() - resetStructuredAgentSessionSendsForTests() - vi.useRealTimers() - useRunningTerminalCloseConfirmStore.getState().dismissRunningTerminalClose() - resetStructuredAgentSessionStatusFeedsForTests() - vi.restoreAllMocks() - }) - - it('stays read across a restart once seen, and a later failure is news again', async () => { - setClock(FAILED_AT) - await connect() - await failStart() - expect(rows()).toEqual([ - expect.objectContaining({ updatedAt: FAILED_AT, stateStartedAt: FAILED_AT }) - ]) - expect(unread()).toBe(1) - setClock(FAILED_AT + 60_000) - acknowledge(FAILED_AT + 60_000) - expect(unread()).toBe(0) - - await restart() - expect(rows()).toEqual([ - expect.objectContaining({ state: 'done', updatedAt: FAILED_AT, stateStartedAt: FAILED_AT }) - ]) - expect(unread()).toBe(0) - expect(tabStatus()).toBe('failed') - - setClock(FAILED_AT + 120_000) - mocks.launch.mockRejectedValueOnce(new StructuredAgentSessionCreateRefusalError('refused')) - act(() => { - retryStructuredAgentSessionLaunch(WORKTREE_ID, SESSION_ID) - }) - await flush() - expect(rows()).toEqual([ - expect.objectContaining({ - stateStartedAt: FAILED_AT + 120_000, - mainAgent: expect.objectContaining({ outcome: 'failure' }) - }) - ]) - expect(unread()).toBe(1) - }) - it('warns during real issued send and accepted handoff before status arrives', async () => { - await ready() - noteStructuredAgentSessionFence(SESSION_ID, 4) - const answer = Promise.withResolvers>() - mocks.call.mockReturnValue(answer.promise) - const sent = sendStructuredAgentSessionMessage({ - sessionId: SESSION_ID, - target: { kind: 'local' }, - text: 'continue' - }) - expect(sent).not.toBeNull() - await flush() - await closeChat() - expect(pendingClose()).not.toBeNull() - useRunningTerminalCloseConfirmStore.getState().dismissRunningTerminalClose() - answer.resolve({ - ok: true, - replayed: false, - fence: 4, - cursor: { epoch: 'e', sequence: 2 }, - value: { - clientMessageId: sent!.clientMessageId, - submission: { - clientMessageId: sent!.clientMessageId, - fence: 4, - payloadFingerprint: 'send', - dispatchState: 'accepted', - providerItemId: null, - reason: null, - submittedAt: 1, - resolvedAt: 2 - } - } - }) - expect(await sent!.outcome).toBe('recorded') - mocks.history.mockResolvedValue({ - ...completeIdle, - page: { ...completeIdle.page, working: true } - }) - await flush() - await closeChat() - await flush() - expect(pendingClose()).not.toBeNull() - expect(store().getState().unifiedTabsByWorktree[WORKTREE_ID]).toContainEqual(structuredTab) - }) -}) diff --git a/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-bridge-unconfirmed-start.test.tsx b/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-bridge-unconfirmed-start.test.tsx deleted file mode 100644 index 6fd6dc649d8..00000000000 --- a/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-bridge-unconfirmed-start.test.tsx +++ /dev/null @@ -1,355 +0,0 @@ -import { markStructuredAgentSessionLaunchCancelled } from '@/lib/agent-session/launch/structured-agent-session-launch-cancel' -// @vitest-environment happy-dom - -// Lost create replies remain unmarked and recheck on reconnect; only confirmed failures earn failure marks. - -import type * as LaunchErrors from '@/lib/agent-session/launch/structured-agent-session-launch-errors' -import { act, cleanup, render, waitFor } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest' -import type { RuntimeMobileSessionTabsResult } from '../../../../../../shared/runtime-session-contracts' -import type { AgentStatusEntry } from '../../../../../../shared/agent-status/contracts/agent-status-types' -import type { Tab } from '../../../../../../shared/tab-types' -import type { StructuredAgentSessionLaunchIntent } from '@/lib/launch-structured-agent-session' -import type { AppState } from '@/store/types' - -type TestStore = { - getState: () => AppState - setState: (state: Partial) => void -} - -const mocks = vi.hoisted(() => { - const hoisted: { - store: TestStore | null - subscribeStatus: Mock - createIntent: Mock - restoreIntent: Mock - launch: Mock< - ( - intent: StructuredAgentSessionLaunchIntent, - onHostSeed?: unknown - ) => Promise<{ sessionId: string; fence: number }> - > - refresh: Mock - history: Mock - } = { - store: null, - subscribeStatus: vi.fn(), - createIntent: vi.fn(), - restoreIntent: vi.fn(), - launch: vi.fn(), - refresh: vi.fn(), - history: vi.fn() - } - return hoisted -}) - -vi.mock('@/store', async () => { - const { createTestStore } = await import('@/store/testing/app-store-test-fixture') - const useAppStore = createTestStore() - mocks.store = useAppStore - return { useAppStore } -}) - -vi.mock('sonner', () => ({ toast: { error: vi.fn(), message: vi.fn() } })) - -vi.mock('@/lib/workspace/ownership/worktree-runtime-owner', () => ({ - getExecutionHostIdForWorktree: () => 'local' -})) - -vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-call', () => ({ - callStructuredAgentSession: mocks.history -})) - -vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ - subscribeStructuredAgentSession: vi.fn(), - subscribeStructuredAgentSessionStatus: mocks.subscribeStatus -})) - -vi.mock('@/runtime/local-structured-session-tabs-sync/inventory-refresh', () => ({ - refreshLocalStructuredSessionTabs: mocks.refresh -})) - -const launchErrorMocks = vi.hoisted(() => { - class StructuredAgentSessionCreateRefusalError extends Error {} - return { StructuredAgentSessionCreateRefusalError } -}) - -vi.mock('@/lib/agent-session/launch/structured-agent-session-launch-errors', async () => ({ - ...(await vi.importActual( - '@/lib/agent-session/launch/structured-agent-session-launch-errors' - )), - ...launchErrorMocks -})) - -vi.mock('@/lib/agent-session/launch/structured-agent-session-launch-create-call', () => ({ - launchStructuredAgentSession: mocks.launch -})) - -vi.mock('@/lib/launch-structured-agent-session', () => { - return { - createStructuredAgentSessionLaunchIntent: mocks.createIntent, - retryStructuredAgentSessionLaunchIntent: vi.fn((prior: unknown) => prior), - restoreStructuredAgentSessionLaunchIntent: mocks.restoreIntent, - abandonStructuredAgentSessionLaunchIntent: vi.fn(), - launchStructuredAgentSession: mocks.launch, - StructuredAgentSessionCreateRefusalError: - launchErrorMocks.StructuredAgentSessionCreateRefusalError - } -}) - -import { StructuredAgentSessionStatusBridge } from './StructuredAgentSessionStatusBridge' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../shared/layout-owner-switch' - -import { startStructuredAgentLaunch } from '@/lib/agent-session/launch/structured-agent-session-launch' -import { - getStructuredAgentSessionLaunchLifecycle, - resetStructuredAgentLaunchRegistryForTests -} from '@/lib/agent-session/launch/structured-agent-session-launch-registry' -import { resetStructuredAgentLaunchPersistenceForTests } from '@/lib/agent-session/launch/structured-agent-session-launch-persistence' -import { recheckUnconfirmedStructuredAgentLaunches } from '@/lib/agent-session/launch/structured-agent-session-launch-unconfirmed-recheck' -import { resetStructuredAgentSessionStatusFeedsForTests } from '@/runtime/native-chat/status/structured-agent-session-status-feed' -import { - resetTerminalTabActivityFlagsCacheForTest, - resolveTerminalTabActivityStatus -} from '../../../tab-bar/terminal-tab-activity-status' - -const WORKTREE_ID = 'wt-1' -const CLAUDE_SESSION = 'session-claude' -const CODEX_SESSION = 'session-codex' - -function chatTab(sessionId: string, agent: 'claude' | 'codex'): Tab { - return { - id: `structured-agent-session-${sessionId}`, - worktreeId: WORKTREE_ID, - groupId: 'group-1', - contentType: 'agent-session', - entityId: sessionId, - label: 'Chat', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1_000, - isPinned: false, - agentSessionAgent: agent - } -} - -function launchIntent( - sessionId: string, - agent: 'claude' | 'codex' = 'claude' -): StructuredAgentSessionLaunchIntent { - return { - worktreeId: WORKTREE_ID, - sessionId, - executionHostId: 'local', - target: { kind: 'local' }, - agent, - params: { - envelope: { - sessionId, - clientOperationId: `operation-${sessionId}`, - expectedRuntimeFence: null, - payloadFingerprint: `fingerprint-${sessionId}` - }, - worktree: `id:${WORKTREE_ID}`, - agent - } - } -} - -function listing(...sessionIds: string[]): RuntimeMobileSessionTabsResult[] { - return [ - { - worktree: WORKTREE_ID, - publicationEpoch: 'epoch-1', - snapshotVersion: 1, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: sessionIds.map((sessionId) => ({ - type: 'agent-session' as const, - id: `agent-session:${sessionId}`, - title: 'Chat', - sessionId, - agent: 'claude' as const, - isActive: false - })) - } - ] -} - -function store(): TestStore { - if (!mocks.store) { - throw new Error('store missing') - } - return mocks.store -} - -function rows(): AgentStatusEntry[] { - return Object.values(store().getState().agentStatusByPaneKey) -} - -function tabStatus(sessionId = CLAUDE_SESSION): string { - const state = store().getState() - return resolveTerminalTabActivityStatus({ - tab: { id: `structured-agent-session-${sessionId}`, title: 'Chat', launchAgent: 'claude' }, - agentStatusByPaneKey: state.agentStatusByPaneKey, - agentStatusEpoch: state.agentStatusEpoch - }) -} - -function lifecycle(sessionId = CLAUDE_SESSION): string | null { - return getStructuredAgentSessionLaunchLifecycle(WORKTREE_ID, sessionId) -} - -function createCalls(): number { - return mocks.launch.mock.calls.length -} - -async function flush(): Promise { - for (let i = 0; i < 30; i += 1) { - await act(async () => { - await Promise.resolve() - }) - } -} - -async function connect(): Promise { - render() - await waitFor(() => expect(mocks.subscribeStatus).toHaveBeenCalled()) - for (const [, emit] of mocks.subscribeStatus.mock.calls) { - act(() => emit({ type: 'snapshot', sessions: [] })) - } -} - -async function reload(): Promise { - cleanup() - store().setState({ agentStatusByPaneKey: {} }) - resetStructuredAgentLaunchRegistryForTests() - resetStructuredAgentLaunchPersistenceForTests() - resetStructuredAgentSessionStatusFeedsForTests() - resetTerminalTabActivityFlagsCacheForTest() - mocks.subscribeStatus.mockClear() - await connect() -} - -async function loseStart( - sessionId = CLAUDE_SESSION, - agent: 'claude' | 'codex' = 'claude' -): Promise { - mocks.createIntent.mockReturnValueOnce(launchIntent(sessionId, agent)) - const launch = startStructuredAgentLaunch(WORKTREE_ID, agent, { - requestId: `request-${sessionId}` - }) - await expect(launch.launchResult).rejects.toThrow('reply lost') - await flush() - expect(lifecycle(sessionId)).toBe('visibility-unknown') -} - -function hostIsReachableAgain(executionHostId: 'local' | `runtime:${string}` = 'local'): void { - act(() => recheckUnconfirmedStructuredAgentLaunches(executionHostId)) -} - -describe('a chat whose start was never confirmed', () => { - beforeEach(() => { - vi.clearAllMocks() - // Queued one-shot answers an earlier case left unconsumed must not leak into the next. - for (const mock of [mocks.createIntent, mocks.launch, mocks.refresh, mocks.restoreIntent]) { - mock.mockReset() - } - localStorage.clear() - resetStructuredAgentLaunchRegistryForTests() - resetStructuredAgentLaunchPersistenceForTests() - resetStructuredAgentSessionStatusFeedsForTests() - resetTerminalTabActivityFlagsCacheForTest() - mocks.subscribeStatus.mockResolvedValue({ unsubscribe: vi.fn() }) - mocks.launch.mockRejectedValue(new Error('reply lost')) - mocks.refresh.mockResolvedValue([]) - mocks.history.mockResolvedValue({ ok: true, page: { fence: 1 } }) - mocks.restoreIntent.mockImplementation((args: { sessionId: string }) => - launchIntent(args.sessionId) - ) - store().setState({ - agentStatusByPaneKey: {}, - acknowledgedAgentsByPaneKey: {}, - retainedAgentsByPaneKey: {}, - unifiedTabsByWorktree: { - [WORKTREE_ID]: [chatTab(CLAUDE_SESSION, 'claude'), chatTab(CODEX_SESSION, 'codex')] - } - }) - }) - - afterEach(() => { - cleanup() - resetStructuredAgentSessionStatusFeedsForTests() - }) - - it('re-checks a start a reload interrupted, without the user pressing Retry', async () => { - await connect() - mocks.createIntent.mockReturnValueOnce(launchIntent(CLAUDE_SESSION)) - mocks.launch.mockReturnValueOnce(new Promise(() => {})) - startStructuredAgentLaunch(WORKTREE_ID, 'claude', { requestId: `request-${CLAUDE_SESSION}` }) - await flush() - - await reload() - expect(lifecycle()).toBe('visibility-unknown') - expect(rows()).toEqual([]) - expect(tabStatus()).not.toBe('failed') - - mocks.launch.mockResolvedValueOnce({ sessionId: CLAUDE_SESSION, fence: 1 }) - mocks.refresh.mockResolvedValueOnce([]).mockResolvedValueOnce(listing(CLAUDE_SESSION)) - hostIsReachableAgain() - await flush() - - expect(mocks.launch).toHaveBeenLastCalledWith( - expect.objectContaining({ - sessionId: CLAUDE_SESSION, - params: expect.objectContaining({ - envelope: expect.objectContaining({ clientOperationId: `operation-${CLAUDE_SESSION}` }) - }) - }), - expect.any(Function), - true, - expect.any(Function) - ) - expect(lifecycle()).toBeNull() - expect(rows()).toEqual([]) - }) - - it('never re-creates a chat the user closed, before or after a reload', async () => { - await connect() - await loseStart(CLAUDE_SESSION, 'claude') - await loseStart(CODEX_SESSION, 'codex') - act(() => { - markStructuredAgentSessionLaunchCancelled( - WORKTREE_ID, - CLAUDE_SESSION, - 'local', - store().getState() - ) - }) - const creates = createCalls() - - hostIsReachableAgain() - await flush() - const recreated = (sessionId: string): number => - mocks.launch.mock.calls.slice(creates).filter(([intent]) => intent.sessionId === sessionId) - .length - expect(recreated(CODEX_SESSION)).toBe(1) - expect(recreated(CLAUDE_SESSION)).toBe(0) - - await reload() - hostIsReachableAgain() - await flush() - expect(recreated(CLAUDE_SESSION)).toBe(0) - if (ORCA_LAYOUT_OWNER_IS_MAIN) { - // Switch-on, main's host is told to close the chat instead of the window keeping a tombstone. - expect(mocks.history).toHaveBeenCalledWith({ kind: 'local' }, 'agentSession.close', { - sessionId: CLAUDE_SESSION - }) - expect(lifecycle(CLAUDE_SESSION)).toBeNull() - } else { - expect(lifecycle(CLAUDE_SESSION)).toBe('cancelled') - } - }) -}) diff --git a/src/renderer/src/components/native-chat/session/structured/delivery/NativeChatMessageList.unsent-message.test.tsx b/src/renderer/src/components/native-chat/session/structured/delivery/NativeChatMessageList.unsent-message.test.tsx deleted file mode 100644 index 844ae2b4b9b..00000000000 --- a/src/renderer/src/components/native-chat/session/structured/delivery/NativeChatMessageList.unsent-message.test.tsx +++ /dev/null @@ -1,224 +0,0 @@ -// @vitest-environment happy-dom - -// Unsent outbox messages stay below newer turns and their activity, without owning a turn bar. - -import '@testing-library/jest-dom/vitest' - -import { cleanup } from '@testing-library/react' -import { render } from '../../../messages/actions/native-chat-tooltip-test-harness' -import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' - -// Why: these fixtures have neither inline visual owners nor sender navigation. -const unusedChatLeaves = vi.hoisted(() => ({ - inlineVisual: vi.fn(() => { - throw new Error('Unexpected inline visual in transcript fixture') - }), - openSender: vi.fn(() => { - throw new Error('Unexpected sender navigation in transcript fixture') - }) -})) -vi.mock('../../../media/visuals/NativeChatInlineVisual', () => ({ - NativeChatInlineVisual: unusedChatLeaves.inlineVisual -})) -vi.mock('@/lib/open-agent-message-sender', () => ({ - openAgentMessageSender: unusedChatLeaves.openSender -})) -afterEach(() => { - expect(unusedChatLeaves.inlineVisual).not.toHaveBeenCalled() - expect(unusedChatLeaves.openSender).not.toHaveBeenCalled() -}) -import type { - AgentJournalItemBody, - AgentJournalRenderItem, - AgentJournalSubmission -} from '../../../../../../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalTurnScope } from '../../../../../../../shared/agent-session/journal/agent-session-journal-turn-scope' -import { agentJournalSubmissionKey } from '../../../../../../../shared/agent-session/journal/agent-session-journal-item-key' -import type { NativeChatSettledTurns } from '../../../../../../../shared/native-chat/transcript/native-chat-turn-status' -import { DISPATCH_REJECTED_HOST_RESTARTED } from '../../../../../../../shared/agent-session/requests/structured-agent-session-dispatch-rejection' -import { NativeChatMessageList } from '../../../NativeChatMessageList' -import { structuredAgentSessionDeliveryNotices } from './structured-agent-session-delivery-notices' -import { installNativeChatMessageListTestViewport } from '../../../viewport/virtualization/native-chat-message-list-test-viewport' -import { projectStructuredAgentSessionMessages } from '../../../conversation/projection/structured-agent-session-message-projection' - -let restoreViewport = (): void => {} -beforeAll(() => { - restoreViewport = installNativeChatMessageListTestViewport() -}) -afterAll(() => restoreViewport()) -afterEach(cleanup) - -type Phase = 'in flight' | 'running' | 'done' - -const SEED = agentJournalSubmissionKey('seed') -const NEW = agentJournalSubmissionKey('new') - -function said(role: 'user' | 'assistant', text: string): AgentJournalItemBody { - return { kind: 'message', role, blocks: [{ type: 'text', text }] } -} - -function journal(phase: Phase, scoped: boolean): AgentJournalRenderItem[] { - const thread: AgentJournalTurnScope = { kind: 'thread' } - const row = ( - itemId: string, - body: AgentJournalItemBody, - turnScope: AgentJournalTurnScope - ): AgentJournalRenderItem => ({ - itemId, - revision: 0, - sequence: rows.length + 1, - observedAt: 1000 + rows.length, - body, - ...(scoped ? { turnScope } : {}) - }) - const rows: AgentJournalRenderItem[] = [] - rows.push(row(SEED, said('user', 'SEED PROMPT'), thread)) - rows.push( - row( - 'turn-seed', - { kind: 'turn', turnId: 'turn-seed', state: 'completed', userItemId: SEED }, - thread - ) - ) - rows.push( - row('seed-answer', said('assistant', 'SEED OK'), { kind: 'turn', turnItemId: 'turn-seed' }) - ) - rows.push(row(NEW, said('user', 'NEW PROMPT'), thread)) - if (phase !== 'in flight') { - rows.push( - row( - 'turn-new', - { - kind: 'turn', - turnId: 'turn-new', - state: phase === 'done' ? 'completed' : 'running', - userItemId: NEW - }, - thread - ) - ) - } - if (phase === 'done') { - rows.push( - row('new-answer', said('assistant', 'NEW OK'), { kind: 'turn', turnItemId: 'turn-new' }) - ) - } - return rows -} - -function submission( - id: string, - dispatchState: AgentJournalSubmission['dispatchState'] -): AgentJournalSubmission { - return { - clientMessageId: id, - fence: 1, - payloadFingerprint: id, - dispatchState, - providerItemId: null, - reason: null, - submittedAt: 1, - resolvedAt: null - } -} - -function drawn(container: HTMLElement): string[] { - const out: string[] = [] - for (const element of container.querySelectorAll('*')) { - if (element.hasAttribute('data-native-chat-turn-activity')) { - out.push('ACTIVITY') - } else if (element.hasAttribute('data-native-chat-turn-status')) { - out.push( - element.getAttribute('data-native-chat-turn-status') === 'active' ? 'WORKING' : 'WORKED' - ) - } else if (element.childElementCount === 0 && (element.textContent ?? '').endsWith('PROMPT')) { - out.push(element.textContent ?? '') - } - } - return out -} - -describe('a message the host rejected after a crash, with no outbox entry left', () => { - const LOST = agentJournalSubmissionKey('lost') - - function hostList(phase: Phase) { - const items = journal(phase, true) - const newIndex = items.findIndex((item) => item.itemId === NEW) - // Recorded between the seed's answer and the newer prompt; the next open rejected it. - items.splice(newIndex, 0, { - itemId: LOST, - revision: 0, - sequence: items[newIndex - 1]!.sequence, - sequenceIndex: 1, - observedAt: 1002.5, - body: said('user', 'LOST PROMPT'), - turnScope: { kind: 'thread' } - }) - const submissions: AgentJournalSubmission[] = [ - submission('seed', 'accepted'), - { - ...submission('lost', 'rejected'), - reason: DISPATCH_REJECTED_HOST_RESTARTED, - rejection: { kind: 'hostRestarted' } - }, - submission('new', phase === 'done' ? 'accepted' : 'pending') - ] - const settledTurns: NativeChatSettledTurns = new Map([ - [SEED, { startedAt: 1, workedSeconds: 3 }], - ...(phase === 'done' ? [[NEW, { startedAt: 2, workedSeconds: 5 }] as const] : []) - ]) - return ( - - ) - } - - it('draws it where it was sent, with its reason and no Retry, outside the newer turn', () => { - const { container, rerender } = render(hostList('running')) - expect(drawn(container)).toEqual([ - 'SEED PROMPT', - 'WORKED', - 'LOST PROMPT', - 'NEW PROMPT', - 'WORKING', - 'ACTIVITY' - ]) - expect(container.textContent).toContain('Orca restarted before this message was sent.') - expect(container.querySelector('button[aria-label="Retry"]')).toBeNull() - expect( - [...container.querySelectorAll('button')].map((button) => button.textContent) - ).not.toContain('Retry') - rerender(hostList('done')) - expect(drawn(container)).toEqual([ - 'SEED PROMPT', - 'WORKED', - 'LOST PROMPT', - 'NEW PROMPT', - 'WORKED' - ]) - expect(container.textContent).toContain('Worked for 5s') - }) -}) diff --git a/src/renderer/src/components/native-chat/subagents/NativeChatMessageList.subagent-sections.test.tsx b/src/renderer/src/components/native-chat/subagents/NativeChatMessageList.subagent-sections.test.tsx deleted file mode 100644 index 78427ceae40..00000000000 --- a/src/renderer/src/components/native-chat/subagents/NativeChatMessageList.subagent-sections.test.tsx +++ /dev/null @@ -1,230 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' - -import { cleanup, fireEvent, screen } from '@testing-library/react' -import { render } from '../messages/actions/native-chat-tooltip-test-harness' - -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -// Why: these fixtures have neither inline visual owners nor sender navigation. -const unusedChatLeaves = vi.hoisted(() => ({ - inlineVisual: vi.fn(() => { - throw new Error('Unexpected inline visual in transcript fixture') - }), - openSender: vi.fn(() => { - throw new Error('Unexpected sender navigation in transcript fixture') - }) -})) -vi.mock('../media/visuals/NativeChatInlineVisual', () => ({ - NativeChatInlineVisual: unusedChatLeaves.inlineVisual -})) -vi.mock('@/lib/open-agent-message-sender', () => ({ - openAgentMessageSender: unusedChatLeaves.openSender -})) -import type { - AgentJournalItemBody, - AgentJournalProducerLinkage, - AgentJournalRenderItem -} from '../../../../../shared/agent-session/journal/agent-session-journal-types' - -import type { NativeChatSubagentState } from '../../../../../shared/native-chat/native-chat-types' - -import { projectStructuredItemsToNativeChat } from '../../../../../shared/agent-session/view/structured-agent-session-projection' - -import { NativeChatMessageList } from '../NativeChatMessageList' - -import { session, stubLayout } from '../viewport/virtualization/native-chat-windowing-test-harness' - -{ - function journalItem( - itemId: string, - body: AgentJournalItemBody, - sequence: number, - linkage: AgentJournalProducerLinkage = {} - ): AgentJournalRenderItem { - return { itemId, body, sequence, observedAt: sequence * 1000, revision: 1, ...linkage } - } - - const child: AgentJournalProducerLinkage = { agentId: 'task-1', producerKind: 'agent' } - const patch = '@@ -1 +1 @@\n-before\n+after' - const itemsWith = ( - state: NativeChatSubagentState, - answered: boolean - ): AgentJournalRenderItem[] => [ - journalItem( - 'ask', - { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Review it' }] }, - 1 - ), - journalItem( - 'spawn', - { - kind: 'message', - role: 'system', - blocks: [ - { - type: 'subagent-group', - groupId: 'group-1', - agents: [{ id: 'task-1', label: 'explore the lane', state }] - } - ] - }, - 2 - ), - journalItem( - 'child-said', - { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'The PR is CLEAN.' }] }, - 3, - child - ), - journalItem( - 'child-edit', - { - kind: 'diff', - path: 'src/a.ts', - patch: { head: patch, truncated: false, digest: 'fixture', byteLength: patch.length } - }, - 4, - child - ), - ...(answered - ? [ - journalItem( - 'answer', - { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: 'Delegated; nothing to fix.' }] - }, - 5 - ) - ] - : []) - ] - - /** `waiting`: the session runs and has produced nothing since the roster. */ - function listOf(state: NativeChatSubagentState, waiting = false): React.JSX.Element { - const items = itemsWith(state, !waiting) - return ( - - ) - } - - describe("a subagent's rows in the transcript", () => { - afterEach(cleanup) - let restoreLayout = (): void => {} - beforeEach(() => { - restoreLayout = stubLayout() - }) - afterEach(() => { - restoreLayout() - vi.restoreAllMocks() - }) - - // Journal turn records own subagent edits, even when a newer send is queued or the opener is unloaded. - it("counts a subagent's edit in the turn the journal says it was made in", () => { - const say = (itemId: string, role: 'user' | 'assistant', text: string, sequence: number) => - journalItem(itemId, { kind: 'message', role, blocks: [{ type: 'text', text }] }, sequence) - const turn = (turnId: string, userItemId: string, sequence: number) => - journalItem( - `turn-${turnId}`, - { kind: 'turn', turnId, state: 'completed', userItemId, startedAt: sequence * 1000 }, - sequence - ) - const childEdit = (itemId: string, path: string, sequence: number) => - journalItem( - itemId, - { - kind: 'diff', - path, - patch: { head: patch, truncated: false, digest: path, byteLength: patch.length } - }, - sequence, - child - ) - const [ask, spawn] = itemsWith('completed', false) - const items = [ - ask!, - turn('1', 'ask', 2), - { ...spawn!, sequence: 3 }, - say('ask-2', 'user', 'And the tests?', 4), - childEdit('child-edit', 'src/a.ts', 5), - say('answer-1', 'assistant', 'Edited a.', 6), - turn('2', 'ask-2', 7), - say('answer-2', 'assistant', 'Tests pass.', 8), - // Its opener is outside the loaded window, so the turn keys to its own record. - turn('3', 'older-send', 9), - childEdit('child-woke', 'src/b.ts', 10), - say('answer-3', 'assistant', 'Picked up the result.', 11) - ] - render( - - ) - const rollups = screen.getAllByRole('button', { name: /src\/[ab].ts/ }) - expect(rollups.map((rollup) => rollup.getAttribute('aria-label'))).toEqual([ - expect.stringMatching(/src\/a.ts/), - expect.stringMatching(/src\/b.ts/) - ]) - const inOrder = [ - screen.getByText('Edited a.'), - rollups[0]!, - screen.getByText('Tests pass.'), - screen.getByText('Picked up the result.'), - rollups[1]! - ] - for (const [index, node] of inOrder.slice(1).entries()) { - expect(inOrder[index]!.compareDocumentPosition(node)).toBe(Node.DOCUMENT_POSITION_FOLLOWING) - } - }) - - it('keeps a roster list open or closed past its row unmounting, and hides its sections while closed', () => { - const items = itemsWith('completed', true) - const view = (withRoster: boolean) => { - const shown = withRoster ? items : items.filter((next) => next.itemId !== 'spawn') - return ( - - ) - } - const { rerender } = render(view(true)) - fireEvent.click(screen.getByRole('button', { name: /Ran 1 subagent/ })) - fireEvent.click(screen.getByRole('button', { name: /explore the lane/, expanded: false })) - expect(screen.getByText('The PR is CLEAN.')).toBeInTheDocument() - - rerender(view(false)) - rerender(view(true)) - expect(screen.getByRole('button', { name: /Ran 1 subagent/, expanded: true })).toBeVisible() - - fireEvent.click(screen.getByRole('button', { name: /Ran 1 subagent/ })) - expect(screen.queryByText('The PR is CLEAN.')).toBeNull() - fireEvent.click(screen.getByRole('button', { name: /Ran 1 subagent/ })) - expect(screen.getByText('The PR is CLEAN.')).toBeInTheDocument() - }) - - it("keeps the reader's choice over the frontier, in either direction", () => { - const { rerender } = render(listOf('working', true)) - fireEvent.click(screen.getByRole('button', { name: /explore the lane/, expanded: true })) - rerender(listOf('working', true)) - expect(screen.queryByText('The PR is CLEAN.')).toBeNull() - - fireEvent.click(screen.getByRole('button', { name: /explore the lane/, expanded: false })) - rerender(listOf('working')) - expect(screen.getByText('The PR is CLEAN.')).toBeInTheDocument() - }) - }) -} diff --git a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatMessageList.test.tsx b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatMessageList.test.tsx deleted file mode 100644 index e3a09e7bfd0..00000000000 --- a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatMessageList.test.tsx +++ /dev/null @@ -1,484 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' - -import { cleanup, fireEvent, screen } from '@testing-library/react' -import { render } from '../../messages/actions/native-chat-tooltip-test-harness' - -import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' - -// Why: these fixtures have neither inline visual owners nor sender navigation. -const unusedChatLeaves = vi.hoisted(() => ({ - inlineVisual: vi.fn(() => { - throw new Error('Unexpected inline visual in transcript fixture') - }), - openSender: vi.fn(() => { - throw new Error('Unexpected sender navigation in transcript fixture') - }) -})) -vi.mock('../../media/visuals/NativeChatInlineVisual', () => ({ - NativeChatInlineVisual: unusedChatLeaves.inlineVisual -})) -vi.mock('@/lib/open-agent-message-sender', () => ({ - openAgentMessageSender: unusedChatLeaves.openSender -})) -afterEach(() => { - expect(unusedChatLeaves.inlineVisual).not.toHaveBeenCalled() - expect(unusedChatLeaves.openSender).not.toHaveBeenCalled() -}) - -import { subagentGroupFallbackText } from '../../../../../../shared/native-chat/transcript/native-chat-subagent-summary' - -import type { - NativeChatMessage, - NativeChatSubagentEntry -} from '../../../../../../shared/native-chat/native-chat-types' - -import type { NativeChatLiveSession } from '../../session/terminal/read/native-chat-live-session-contract' - -import { NativeChatMessageList } from '../../NativeChatMessageList' - -import { installNativeChatMessageListTestViewport } from '../../viewport/virtualization/native-chat-message-list-test-viewport' - -import type { AgentJournalRenderItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalTurnScope } from '../../../../../../shared/agent-session/journal/agent-session-journal-turn-scope' - -{ - const session: NativeChatLiveSession = { - messages: [ - { - id: 'assistant-1', - role: 'assistant', - blocks: [{ type: 'text', text: 'Selectable agent response.' }], - timestamp: 1, - source: 'transcript' - } - ], - status: 'ready', - sessionId: 'session-1', - agent: 'codex', - hasMore: false, - loadingEarlier: false, - olderHistoryGeneration: 0, - loadEarlier: vi.fn(), - readPhase: 'ready' - } - - describe('NativeChatMessageList assistant messages', () => { - let restoreViewport = (): void => {} - beforeAll(() => { - restoreViewport = installNativeChatMessageListTestViewport() - }) - afterAll(() => restoreViewport()) - afterEach(cleanup) - it.each([true, false])( - 'copies selections across message roots from the transcript (math=%s)', - (math) => { - const sources = math - ? ['Before $x^2$ after.', 'Then \\(y_i\\).'] - : ['Before plain after.', 'Then plain.'] - const view = render( - ({ - id: `selection-${index}`, - role: 'assistant', - blocks: [{ type: 'text', text }], - timestamp: index + 1, - source: 'transcript' - })) - }} - isWorking={false} - expandSignal={false} - /> - ) - const transcript = view.container.querySelector('[data-native-chat-scroll]') - const paragraphs = view.container.querySelectorAll('[data-native-chat-quote-source] p') - if (!transcript || paragraphs.length !== 2) { - throw new Error('Missing transcript paragraphs') - } - const range = document.createRange() - range.setStart(paragraphs[0].firstChild ?? paragraphs[0], 0) - range.setEnd(paragraphs[1], paragraphs[1].childNodes.length) - const selection = document.getSelection() - selection?.removeAllRanges() - selection?.addRange(range) - for (const target of [paragraphs[0], transcript]) { - const setData = vi.fn() - const event = new Event('copy', { bubbles: true, cancelable: true }) - Object.defineProperty(event, 'clipboardData', { value: { setData } }) - fireEvent(target, event) - if (math) { - const copied = setData.mock.calls.find(([type]) => type === 'text/plain')?.[1] - expect(copied).toBe(sources.join('\n\n')) - expect(event.defaultPrevented).toBe(true) - } else { - expect(setData).not.toHaveBeenCalled() - expect(event.defaultPrevented).toBe(false) - } - } - const setData = vi.fn() - const handled = new Event('copy', { bubbles: true, cancelable: true }) - handled.preventDefault() - Object.defineProperty(handled, 'clipboardData', { value: { setData } }) - fireEvent(transcript, handled) - expect(setData).not.toHaveBeenCalled() - selection?.removeAllRanges() - } - ) - - // Prose settles the preceding run; reasoning asides remain inside it. - it('settles a run once prose follows it, but not for a reasoning aside', () => { - const run = { - id: 'assistant-tool-1', - role: 'assistant' as const, - blocks: [ - { - type: 'tool-call' as const, - name: 'shell', - input: { command: 'sleep 5' }, - state: 'running' as const - } - ], - timestamp: 1, - source: 'transcript' as const - } - const after = (role: 'assistant' | 'reasoning') => ({ - id: `after-${role}`, - role, - blocks: [{ type: 'text' as const, text: 'Looking at the output.' }], - timestamp: 2, - source: 'transcript' as const - }) - const { rerender } = render( - - ) - expect(screen.getByText('Running 1 command')).toBeInTheDocument() - - rerender( - - ) - expect(screen.queryByText('Running 1 command')).toBeNull() - expect(screen.getByText('sleep 5')).toBeInTheDocument() - }) - - it('keeps the current tool live when a stale completed lifecycle meets active hook state', () => { - render( - - ) - - expect(screen.getByText('Running 1 command')).toBeInTheDocument() - expect(screen.getByText('sleep 5')).toBeInTheDocument() - }) - }) - - // Exercise list assembly: folding, turn mapping and disclosure decide whether roster rows reach the DOM. - describe('NativeChatMessageList spawn-group roster', () => { - let restoreViewport = (): void => {} - beforeAll(() => { - restoreViewport = installNativeChatMessageListTestViewport() - }) - afterAll(() => restoreViewport()) - afterEach(cleanup) - const ROSTER: NativeChatSubagentEntry[] = [ - { id: 'a', label: 'read', state: 'completed' }, - { id: 'b', label: 'search', state: 'failed' } - ] - - /** Match the producer’s structured roster plus plain-text fallback for older clients. */ - function rosterMessage(agents: NativeChatSubagentEntry[], at: number): NativeChatMessage { - return { - id: 'roster-1', - role: 'system', - blocks: [ - { type: 'text', text: subagentGroupFallbackText(agents) }, - { type: 'subagent-group', groupId: 'thread-1:turn-1', agents } - ], - timestamp: at, - source: 'transcript' - } - } - - // Use ascending timestamps; equal times sort by id and can move the opener after its roster. - function rosterSession( - agents: NativeChatSubagentEntry[], - startedAt: number - ): NativeChatLiveSession { - return { - ...session, - status: 'ready', - messages: [ - { - id: 'user-fanout', - role: 'user', - blocks: [{ type: 'text', text: 'Fan this out' }], - timestamp: startedAt, - source: 'transcript' - }, - { - id: 'assistant-fanout', - role: 'assistant', - blocks: [ - { type: 'tool-call', name: 'shell', input: { command: 'pwd' }, state: 'completed' }, - { type: 'tool-result', output: '/repo' } - ], - timestamp: startedAt + 1, - source: 'transcript' - }, - rosterMessage(agents, startedAt + 2) - ] - } - } - - // Providers may fold a roster beside real prose; remove only its fallback twin. - it('keeps prose beside a roster block and drops only the twin', () => { - const startedAt = Date.now() - 3000 - const twin = subagentGroupFallbackText(ROSTER) - render( - - ) - - expect(screen.getByText('Handing the audit to two children.')).toBeInTheDocument() - expect(screen.getByRole('button', { name: /Ran 2 subagents/ })).toBeInTheDocument() - expect(screen.queryByText(twin)).toBeNull() - }) - - // A newer turn must not turn still-running children into completed or unverifiable agents. - it('keeps live children working after a newer turn supersedes their own', () => { - const startedAt = Date.now() - 3000 - const live = rosterSession( - [ - { id: 'a', label: 'read_readme', state: 'working', startedAt }, - { id: 'b', label: 'read_package', state: 'working', startedAt } - ], - startedAt - ) - render( - - ) - - const roster = screen.getByRole('button', { name: /Kicked off 2 subagents/ }) - expect(roster).toHaveTextContent('2 working') - expect(roster).not.toHaveTextContent('unverifiable') - expect(screen.queryByRole('button', { name: /Ran 2 subagents/ })).toBeNull() - }) - }) -} - -{ - const NARRATION = 'I am starting with the required readiness pass.' - const MORE_NARRATION = 'The branch is current and the reference corpus is refreshed.' - const ANSWER = 'Review complete: clean after fixes.' - - function session(startedAt: number): NativeChatLiveSession { - return { - messages: [ - { - id: 'user-1', - role: 'user', - blocks: [{ type: 'text', text: 'Please review this PR.' }], - timestamp: startedAt, - source: 'transcript' - }, - { - id: 'narration-1', - role: 'assistant', - blocks: [{ type: 'text', text: NARRATION }], - timestamp: startedAt + 1, - source: 'transcript' - }, - { - id: 'work-1', - role: 'assistant', - blocks: [ - { - type: 'tool-call', - name: 'shell', - input: { command: 'pnpm test' }, - state: 'completed' - }, - { type: 'tool-result', output: 'ok' } - ], - timestamp: startedAt + 2, - source: 'transcript' - }, - { - id: 'narration-2', - role: 'assistant', - blocks: [{ type: 'text', text: MORE_NARRATION }], - timestamp: startedAt + 3, - source: 'transcript' - }, - { - id: 'answer-1', - role: 'assistant', - blocks: [{ type: 'text', text: ANSWER }], - timestamp: startedAt + 4, - source: 'transcript' - } - ], - status: 'ready', - sessionId: 'session-1', - agent: 'codex', - hasMore: false, - loadingEarlier: false, - olderHistoryGeneration: 0, - loadEarlier: vi.fn(), - readPhase: 'ready' - } - } - - /** One turn owns every later row; statesScope=false models older hosts without row scopes. */ - function journalOf( - messages: readonly NativeChatMessage[], - statesScope: boolean - ): AgentJournalRenderItem[] { - const scope = (turnScope: AgentJournalTurnScope) => (statesScope ? { turnScope } : {}) - const [opener, ...rest] = messages - const entry = (message: NativeChatMessage, sequence: number): AgentJournalRenderItem => ({ - itemId: message.id, - revision: 0, - sequence, - observedAt: sequence, - body: { - kind: 'message', - role: message.role === 'user' ? 'user' : 'assistant', - blocks: [{ type: 'text', text: message.id }] - }, - ...scope({ kind: 'turn', turnItemId: 'turn-1' }) - }) - return [ - { ...entry(opener!, 1), ...scope({ kind: 'thread' }) }, - { - itemId: 'turn-1', - revision: 0, - sequence: 2, - observedAt: 2, - body: { kind: 'turn', turnId: 'turn-1', state: 'completed', userItemId: opener!.id }, - ...scope({ kind: 'thread' }) - }, - ...rest.map((message, index) => entry(message, index + 3)) - ] - } - - describe('NativeChatMessageList settled turn fold', () => { - let restoreViewport = (): void => {} - beforeAll(() => { - restoreViewport = installNativeChatMessageListTestViewport() - }) - afterAll(() => restoreViewport()) - afterEach(cleanup) - - // A mid-turn steer remains in the opener’s fold without gaining its own turn bar. - it.each([ - ['states each row’s turn', true], - ['states no scope', false] - ])( - "folds the rows after a mid-turn send behind the opener's bar on a host that %s", - (_host, statesScope) => { - const startedAt = Date.now() - 3000 - const base = session(startedAt) - const steer: (typeof base.messages)[number] = { - id: 'mid-b', - role: 'user', - blocks: [{ type: 'text', text: 'Also check the tests.' }], - timestamp: startedAt + 2, - source: 'transcript' - } - const messages = [...base.messages.slice(0, 3), steer, ...base.messages.slice(3)] - render( - - ) - - expect(screen.getByText('Also check the tests.')).toBeInTheDocument() - expect(screen.queryByText(NARRATION)).toBeNull() - expect(screen.queryByText(MORE_NARRATION)).toBeNull() - const toggles = screen.getAllByRole('button', { name: 'Toggle turn details' }) - expect(toggles).toHaveLength(1) - - fireEvent.click(toggles[0]!) - expect(screen.getByText(NARRATION)).toBeInTheDocument() - expect(screen.getByText(MORE_NARRATION)).toBeInTheDocument() - } - ) - }) -} diff --git a/src/renderer/src/components/native-chat/tools/runs/NativeChatBrowserPageButton.test.tsx b/src/renderer/src/components/native-chat/tools/runs/NativeChatBrowserPageButton.test.tsx index 50845d73e13..1ef00b0357f 100644 --- a/src/renderer/src/components/native-chat/tools/runs/NativeChatBrowserPageButton.test.tsx +++ b/src/renderer/src/components/native-chat/tools/runs/NativeChatBrowserPageButton.test.tsx @@ -1,6 +1,6 @@ // @vitest-environment happy-dom -import { act, render, screen } from '@testing-library/react' +import { act, render, screen, within } from '@testing-library/react' import type { ReactNode } from 'react' import { describe, expect, it, vi } from 'vitest' import type { BrowserPage } from '../../../../../../shared/browser-workspace-types' @@ -71,4 +71,29 @@ describe('NativeChatBrowserRunPageButton', () => { act(() => setBrowserAgentPageActive('p2', true, 'wt-1')) expect(screen.getByRole('button').getAttribute('title')).toBe('First') }) + + it("ignores other agents driving a different page before this run's command lands", () => { + state.browserPagesByWorkspace = { 'ws-1': [page('p1', 'Mine'), page('p2', 'Theirs')] } + // An earlier run in this chat, so it is known to claim its activity. + setBrowserAgentPageActive('p1', true, 'wt-1', undefined, 'session-1') + const { container } = render( + , + { wrapper } + ) + + act(() => setBrowserAgentPageActive('p2', true, 'wt-1')) + act(() => setBrowserAgentPageActive('p2', true, 'wt-1', undefined, 'session-2')) + act(() => setBrowserAgentPageActive('p1', true, 'wt-1', undefined, 'session-1')) + act(() => setBrowserAgentPageActive('p2', true, 'wt-1')) + expect(within(container).getByRole('button').getAttribute('title')).toBe('Mine') + }) }) diff --git a/src/renderer/src/components/native-chat/tools/runs/NativeChatBrowserPageButton.tsx b/src/renderer/src/components/native-chat/tools/runs/NativeChatBrowserPageButton.tsx index ccd667ade63..d11c156f520 100644 --- a/src/renderer/src/components/native-chat/tools/runs/NativeChatBrowserPageButton.tsx +++ b/src/renderer/src/components/native-chat/tools/runs/NativeChatBrowserPageButton.tsx @@ -62,7 +62,7 @@ function BrowserPageButton({ }): React.JSX.Element | null { const t = useTranslate() const owner = useNativeChatVisualOwner() - const latest = useLastBrowserAgentActivity(owner?.worktreeId ?? null) + const latest = useLastBrowserAgentActivity(owner?.worktreeId ?? null, owner?.sessionId ?? null) // A call appears before its command reaches the browser, so only later activity is its own. const [baseline, setBaseline] = useState(() => startRun(runCallId)) if (baseline.runCallId !== runCallId) { diff --git a/src/renderer/src/components/native-chat/usage/NativeChatUsageLimitActions.tsx b/src/renderer/src/components/native-chat/usage/NativeChatUsageLimitActions.tsx index 5621382fb1a..ba2673addc3 100644 --- a/src/renderer/src/components/native-chat/usage/NativeChatUsageLimitActions.tsx +++ b/src/renderer/src/components/native-chat/usage/NativeChatUsageLimitActions.tsx @@ -5,34 +5,30 @@ import { useLayoutEffect, useMemo, useRef, - useState, - type ReactNode + useState } from 'react' +import type { ReactNode } from 'react' import { MessageSquarePlus } from 'lucide-react' import { Button } from '@/components/ui/button' import { useTranslate } from '@/i18n/use-translate' import { useAppStore } from '@/store/index' -import { structuredChatTabById } from '@/lib/structured-chat-tab-index' +import { structuredChatTabById } from '@/lib/agent-session/tab-identity/structured-chat-tab-index' import { useStructuredChatTabConversationName } from '@/runtime/native-chat/naming/structured-conversation-name' import { AgentSessionContinuationDialog } from '@/components/agent-session-continuation/AgentSessionContinuationDialog' -import { - buildAgentSessionContinuationPrompt, - type AgentSessionContinuationRequest -} from '@/lib/agent-session/context/agent-session-continuation' +import { buildAgentSessionContinuationPrompt } from '@/lib/agent-session/context/agent-session-continuation' +import type { AgentSessionContinuationRequest } from '@/lib/agent-session/context/agent-session-continuation' import { ClaudeSwitcherMenu } from '@/components/status-bar/ClaudeSwitcherMenu' import { ProviderAccountChatButton } from '@/components/status-bar/ProviderAccountChatButton' import { isTuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent-config' import { callStructuredAgentSession } from '@/runtime/native-chat/requests/structured-agent-session-call' -import type { AgentSessionOptionsResult } from '../../../../../shared/agent-session/options/agent-session-options-result' import { executionHostIdForStructuredTarget } from '@/runtime/native-chat/session-ownership/structured-agent-session-owner' -import { - NativeChatOrcaStopContext, - type NativeChatOrcaStopView -} from '@/components/native-chat/messages/notices/native-chat-orca-stop-context' +import { NativeChatOrcaStopContext } from '@/components/native-chat/messages/notices/native-chat-orca-stop-context' +import type { NativeChatOrcaStopView } from '@/components/native-chat/messages/notices/native-chat-orca-stop-context' +import { nativeChatMessageCopyText } from '../../../../../shared/native-chat/transcript/native-chat-message-copy-text' +import type { AgentSessionOptionsResult } from '../../../../../shared/agent-session/options/agent-session-options-result' import type { NativeChatMessage } from '../../../../../shared/native-chat/native-chat-types' import type { NativeChatStructuredViewProps } from '@/components/native-chat/native-chat-view-types' import type { NativeChatFileLinkContext } from '@/components/native-chat/links/actions/native-chat-file-link-context' -import { nativeChatMessageCopyText } from '../../../../../shared/native-chat/transcript/native-chat-message-copy-text' type UsageLimitActions = { account: ReactNode diff --git a/src/renderer/src/components/native-chat/viewport/history/NativeChatMessageList.older-history.test.tsx b/src/renderer/src/components/native-chat/viewport/history/NativeChatMessageList.older-history.test.tsx deleted file mode 100644 index 14df9d4defa..00000000000 --- a/src/renderer/src/components/native-chat/viewport/history/NativeChatMessageList.older-history.test.tsx +++ /dev/null @@ -1,429 +0,0 @@ -// @vitest-environment happy-dom -import { createRef, useSyncExternalStore } from 'react' -import type { NativeChatMessageListHandle } from '../../messages/actions/use-native-chat-reveal-latest' - -import '@testing-library/jest-dom/vitest' - -import { act, cleanup, fireEvent, screen } from '@testing-library/react' -import { render } from '../../messages/actions/native-chat-tooltip-test-harness' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -// Why: these fixtures have neither inline visual owners nor sender navigation. -const historyHost = vi.hoisted(() => ({ call: vi.fn(), subscribe: vi.fn() })) -vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-call', () => ({ - callStructuredAgentSession: historyHost.call -})) - -vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ - subscribeStructuredAgentSession: historyHost.subscribe -})) - -const unusedChatLeaves = vi.hoisted(() => ({ - inlineVisual: vi.fn(() => { - throw new Error('Unexpected inline visual in transcript fixture') - }), - openSender: vi.fn(() => { - throw new Error('Unexpected sender navigation in transcript fixture') - }) -})) -vi.mock('../../media/visuals/NativeChatInlineVisual', () => ({ - NativeChatInlineVisual: unusedChatLeaves.inlineVisual -})) -vi.mock('@/lib/open-agent-message-sender', () => ({ - openAgentMessageSender: unusedChatLeaves.openSender -})) -afterEach(() => { - expect(unusedChatLeaves.inlineVisual).not.toHaveBeenCalled() - expect(unusedChatLeaves.openSender).not.toHaveBeenCalled() -}) -import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' -import { NativeChatMessageList } from '../../NativeChatMessageList' -import { createReadOwner } from '../../session/structured/read/structured-agent-session-read-owner-create' -import type { AgentSessionHistoryPage } from '../../../../../../shared/agent-session/agent-session-wire' -import { useAppStore } from '@/store' -import { transcriptWindowTop } from '../virtualization/native-chat-window-test-layout' -import type { NativeChatOlderPageResult } from './native-chat-pagination' -import type { NativeChatLiveSession } from '../../session/terminal/read/native-chat-live-session-contract' - -import { - layout, - marker, - session, - stubLayout, - stubResizeObserver -} from '../virtualization/native-chat-windowing-test-harness' - -// Unlike happy-dom, report on observe and whenever the sentinel crosses the prefetch edge. -type FakeObservation = { - callback: IntersectionObserverCallback - observer: IntersectionObserver - targets: Map -} -const observations = new Set() -const createdObservers: { root: Element | Document | null; rootMargin: string }[] = [] -let sentinelInRange = false - -class FakeIntersectionObserver implements IntersectionObserver { - readonly root: Element | Document | null - readonly rootMargin: string - readonly scrollMargin = '0px' - readonly thresholds: readonly number[] = [0] - private readonly observation: FakeObservation - constructor(callback: IntersectionObserverCallback, options: IntersectionObserverInit = {}) { - this.root = options.root ?? null - this.rootMargin = options.rootMargin ?? '0px' - this.observation = { callback, observer: this, targets: new Map() } - observations.add(this.observation) - createdObservers.push({ root: this.root, rootMargin: this.rootMargin }) - } - observe(target: Element): void { - this.observation.targets.set(target, null) - } - unobserve(target: Element): void { - this.observation.targets.delete(target) - } - disconnect(): void { - this.observation.targets.clear() - observations.delete(this.observation) - } - takeRecords(): IntersectionObserverEntry[] { - return [] - } -} - -function deliverIntersections(): void { - act(() => { - for (const observation of Array.from(observations)) { - const entries: IntersectionObserverEntry[] = [] - for (const [target, last] of observation.targets) { - if (last !== sentinelInRange) { - observation.targets.set(target, sentinelInRange) - entries.push({ - boundingClientRect: new DOMRect(), - intersectionRatio: sentinelInRange ? 1 : 0, - intersectionRect: new DOMRect(), - isIntersecting: sentinelInRange, - rootBounds: null, - target, - time: 0 - }) - } - } - if (entries.length > 0) { - observation.callback(entries, observation.observer) - } - } - }) -} - -async function settle(): Promise { - await act(async () => {}) -} - -const markers = (from: number, to: number): NativeChatMessage[] => - Array.from({ length: to - from }, (_, offset) => marker(from + offset)) - -/** The scroll root's `pt-10`, and the transcript column's `gap-5`. */ -const TOP_GUTTER_PX = 40 -const COLUMN_GAP_PX = 20 -/** In-flow chrome offsets the spacer by its height plus one flex-column gap. */ -const IN_FLOW_CHROME_PX = 32 - -function flowAboveSpacer(spacer: HTMLElement): number { - return transcriptWindowTop(spacer, TOP_GUTTER_PX, IN_FLOW_CHROME_PX + COLUMN_GAP_PX) -} - -type LoadEarlier = () => Promise - -function paging({ - messages, - loadEarlier, - hasMore = true, - loadingEarlier = false, - isVisible = true, - olderHistoryGeneration = 0, - readPhase = 'ready' -}: { - messages: NativeChatMessage[] - loadEarlier: LoadEarlier - hasMore?: boolean - loadingEarlier?: boolean - isVisible?: boolean - olderHistoryGeneration?: number - readPhase?: NativeChatLiveSession['readPhase'] -}): React.JSX.Element { - return ( - - ) -} - -afterEach(cleanup) - -describe('older history auto-load', () => { - let restoreLayout = (): void => {} - let restoreResizeObserver = (): void => {} - beforeEach(() => { - restoreLayout = stubLayout({ scrollGeometry: true, offsetChain: true }) - restoreResizeObserver = stubResizeObserver() - vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver) - observations.clear() - createdObservers.length = 0 - sentinelInRange = false - layout.aboveTranscriptPx = 0 - layout.aboveSpacerPx = flowAboveSpacer - }) - afterEach(() => { - vi.useRealTimers() - vi.unstubAllGlobals() - restoreResizeObserver() - restoreLayout() - layout.aboveTranscriptPx = 0 - layout.aboveSpacerPx = null - }) - - it('keeps a returned window bounded through an intersecting sentinel and resumes on manual history intent', async () => { - restoreLayout() - restoreLayout = stubLayout({ - scrollGeometry: true, - offsetChain: true, - viewportHeight: () => 50 - }) - const handle = createRef() - let generation = 0 - let hasMore = true - const loadEarlier = vi.fn(async (): Promise => { - generation++ - hasMore = false - refresh() - return 'applied' - }) - const trimHistory = () => { - generation++ - refresh() - } - const element = () => ( - - ) - const view = render(element()) - function refresh() { - view.rerender(element()) - } - await settle() - // A send while already following preserves initial autofill. - act(() => handle.current?.revealLatest(true)) - expect(generation).toBe(0) - const scroller = view.container.querySelector('[data-native-chat-scroll]')! - fireEvent.wheel(scroller, { deltaY: -20 }) - scroller.scrollTop -= 20 - fireEvent.scroll(scroller) - // The send's near-end predicate remains true after a real departure. - act(() => handle.current?.revealLatest(true)) - sentinelInRange = true - deliverIntersections() - await settle() - deliverIntersections() - await settle() - expect(loadEarlier).not.toHaveBeenCalled() - fireEvent.click(screen.getByRole('button', { name: 'Load earlier messages' })) - await settle() - deliverIntersections() - expect(loadEarlier).toHaveBeenCalledOnce() - expect(screen.queryByRole('button', { name: 'Load earlier messages' })).toBeNull() - }) - - it('retires shared initial autofill across two views and still pages after deliberate history intent', async () => { - restoreLayout() - restoreLayout = stubLayout({ - scrollGeometry: true, - offsetChain: true, - viewportHeight: () => 50 - }) - const page = (oldest: number, direction: 'tail' | 'before'): AgentSessionHistoryPage => ({ - sessionId: 'shared-history', - epoch: 'epoch', - direction, - items: Array.from({ length: 200 }, (_, index) => ({ - itemId: `item-${oldest + index}`, - revision: 1, - sequence: oldest + index, - observedAt: oldest + index, - body: { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: 'folded history' }] - } - })), - removedItemIds: [], - submissions: [], - window: { - oldest: { epoch: 'epoch', sequence: oldest }, - newest: { epoch: 'epoch', sequence: oldest + 199 }, - nextCursor: { epoch: 'epoch', sequence: oldest } - }, - liveCursor: { epoch: 'epoch', sequence: 2000 }, - hasOlder: true, - hasNewer: false - }) - historyHost.subscribe.mockResolvedValue({ unsubscribe: () => {} }) - historyHost.call.mockImplementation(async (_target, method, params) => { - if (method !== 'agentSession.history') { - throw new Error('Unexpected host call') - } - return { ok: true, page: page(params.cursor.sequence - 200, 'before') } - }) - const owner = createReadOwner('shared-history-test', 'shared-history', { kind: 'local' }) - owner.publishCreated(page(1801, 'tail')) - const deactivate = owner.activate({ - getState: useAppStore.getState, - subscribeRetryNow: () => () => {} - }) - const handle = createRef() - function View({ first = false }: { first?: boolean }) { - const snapshot = useSyncExternalStore(owner.subscribe, owner.getSnapshot) - return ( - - ) - } - try { - // Prime expanded source history before the live edge becomes intersecting. - for (let pageIndex = 0; pageIndex < 6; pageIndex++) { - await owner.loadOlder() - } - const view = render( - <> - - - - ) - await settle() - historyHost.call.mockClear() - const scroller = view.container.querySelector('[data-native-chat-scroll]')! - fireEvent.wheel(scroller, { deltaY: -20 }) - scroller.scrollTop -= 20 - fireEvent.scroll(scroller) - act(() => handle.current?.revealLatest(true)) - expect(owner.getSnapshot().state.items).toHaveLength(1024) - sentinelInRange = true - deliverIntersections() - await settle() - deliverIntersections() - await settle() - expect(historyHost.call).not.toHaveBeenCalled() - fireEvent.click(screen.getAllByRole('button', { name: 'Load earlier messages' })[1]!) - await settle() - expect(historyHost.call).toHaveBeenCalledOnce() - expect(owner.getSnapshot().state.items).toHaveLength(1224) - view.unmount() - } finally { - deactivate() - owner.dispose() - } - }) - - it('offers a manual load after a failed page, and resumes auto-loading once it succeeds', async () => { - const loadEarlier = vi - .fn() - .mockResolvedValueOnce('failed') - .mockResolvedValue('applied') - const base = markers(100, 150) - const { rerender } = render(paging({ messages: base, loadEarlier })) - sentinelInRange = true - deliverIntersections() - await settle() - - const retry = screen.getByRole('button', { name: 'Load earlier messages' }) - expect(screen.queryByRole('status')).not.toBeInTheDocument() - expect(observations.size).toBe(0) - sentinelInRange = false - deliverIntersections() - sentinelInRange = true - deliverIntersections() - expect(loadEarlier).toHaveBeenCalledTimes(1) - - fireEvent.click(retry) - await settle() - expect(loadEarlier).toHaveBeenCalledTimes(2) - expect(screen.queryByRole('button', { name: /load earlier/i })).not.toBeInTheDocument() - expect(screen.getByRole('status')).toBeInTheDocument() - - rerender(paging({ messages: base, loadEarlier, loadingEarlier: true })) - rerender(paging({ messages: [...markers(80, 100), ...base], loadEarlier })) - deliverIntersections() - expect(loadEarlier).toHaveBeenCalledTimes(3) - }) - - // Without this the recreated observer would ask for the same stuck page forever. - it('stops auto-loading, and offers a manual load, when a page made no progress', async () => { - const loadEarlier = vi.fn().mockResolvedValue('unchanged') - const base = markers(100, 150) - const { rerender } = render(paging({ messages: base, loadEarlier })) - sentinelInRange = true - deliverIntersections() - rerender(paging({ messages: base, loadEarlier, loadingEarlier: true })) - rerender(paging({ messages: base, loadEarlier })) - await settle() - deliverIntersections() - - expect(loadEarlier).toHaveBeenCalledTimes(1) - expect(observations.size).toBe(0) - expect(screen.getByRole('button', { name: 'Load earlier messages' })).toBeInTheDocument() - }) - - // Reconnect/reset starts a new paging generation and clears that generation’s failure. - it('resumes auto-loading, with no click, once the lane resets its paging generation', async () => { - const loadEarlier = vi - .fn() - .mockResolvedValueOnce('failed') - .mockResolvedValue('applied') - const base = markers(100, 150) - const { rerender } = render(paging({ messages: base, loadEarlier })) - sentinelInRange = true - deliverIntersections() - await settle() - expect(screen.getByRole('button', { name: 'Load earlier messages' })).toBeInTheDocument() - - rerender(paging({ messages: base, loadEarlier, olderHistoryGeneration: 1 })) - deliverIntersections() - - expect(loadEarlier).toHaveBeenCalledTimes(2) - expect(screen.queryByRole('button', { name: /load earlier/i })).not.toBeInTheDocument() - }) -}) diff --git a/src/renderer/src/components/native-chat/viewport/navigation/NativeChatMessageList.rail-history-jump.test.tsx b/src/renderer/src/components/native-chat/viewport/navigation/NativeChatMessageList.rail-history-jump.test.tsx deleted file mode 100644 index f4e5b364816..00000000000 --- a/src/renderer/src/components/native-chat/viewport/navigation/NativeChatMessageList.rail-history-jump.test.tsx +++ /dev/null @@ -1,354 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' - -import { act, cleanup, fireEvent, screen } from '@testing-library/react' -import { render } from '../../messages/actions/native-chat-tooltip-test-harness' -import { useCallback, useMemo, useState } from 'react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -// Why: these fixtures have neither inline visual owners nor sender navigation. -const unusedChatLeaves = vi.hoisted(() => ({ - inlineVisual: vi.fn(() => { - throw new Error('Unexpected inline visual in transcript fixture') - }), - openSender: vi.fn(() => { - throw new Error('Unexpected sender navigation in transcript fixture') - }) -})) -vi.mock('../../media/visuals/NativeChatInlineVisual', () => ({ - NativeChatInlineVisual: unusedChatLeaves.inlineVisual -})) -vi.mock('@/lib/open-agent-message-sender', () => ({ - openAgentMessageSender: unusedChatLeaves.openSender -})) -afterEach(() => { - expect(unusedChatLeaves.inlineVisual).not.toHaveBeenCalled() - expect(unusedChatLeaves.openSender).not.toHaveBeenCalled() -}) -import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' -import { NativeChatMessageList } from '../../NativeChatMessageList' -import { - transcriptRowOffset, - transcriptWindowTop -} from '../virtualization/native-chat-window-test-layout' -import type { NativeChatRailOutlineEntry } from '../rail/native-chat-message-rail-items' -import type { NativeChatOlderPageResult } from '../history/native-chat-pagination' -import { - estimateNativeChatRowHeight, - nativeChatRowContentMetrics -} from '../virtualization/native-chat-row-height-estimate' -import { - deliverResizes, - layout, - marker, - overrideLayoutProperty, - session, - stubLayout, - stubResizeObserver -} from '../virtualization/native-chat-windowing-test-harness' - -afterEach(cleanup) - -const TOTAL = 60 -const PAGE = 20 -/** The scroll root's top gutter, always present. */ -const TOP_GUTTER_PX = 40 -/** In-flow older-history chrome disappears with the last page. */ -const OLDER_HISTORY_ROW_PX = 52 - -function message(index: number): NativeChatMessage { - return index % 5 === 0 - ? { - id: `message-${index}`, - role: 'user', - blocks: [{ type: 'text', text: `prompt-${index}` }], - timestamp: index + 1, - source: 'transcript' - } - : marker(index) -} - -const HISTORY = Array.from({ length: TOTAL }, (_, index) => message(index)) - -/** Every row measures exactly as estimated, so nothing but the jump moves the view. */ -const ROW_HEIGHT_BY_TEXT = new Map( - HISTORY.map((entry) => [ - entry.blocks[0]?.type === 'text' ? entry.blocks[0].text : '', - estimateNativeChatRowHeight(nativeChatRowContentMetrics(entry), { - hasReceipt: false, - hasStatus: false, - hasTurnDiff: false - }) - ]) -) - -/** Publish each page before settling its promise; the outline also includes unloaded prompts. */ -function PagedTranscript({ - holdPage -}: { - /** Awaited before a page lands, to keep it in flight. */ - holdPage?: () => Promise -}): React.JSX.Element { - const [loaded, setLoaded] = useState(PAGE) - const loadEarlier = useCallback(async (): Promise => { - await (holdPage?.() ?? Promise.resolve()) - setLoaded((current) => Math.min(TOTAL, current + PAGE)) - return 'applied' - }, [holdPage]) - const messages = useMemo(() => HISTORY.slice(TOTAL - loaded), [loaded]) - const railOutline = useMemo( - () => - HISTORY.slice(0, TOTAL - loaded) - .filter((entry) => entry.role === 'user') - .map((entry) => ({ - id: entry.id, - text: entry.blocks[0]?.type === 'text' ? entry.blocks[0].text : '', - hasImages: false - })), - [loaded] - ) - return ( - - ) -} - -function rowText(row: HTMLElement): string { - return /(?:prompt|marker)-\d+/.exec(row.querySelector('p')?.textContent ?? '')?.[0] ?? '' -} - -// A jump must detach end-follow and retain its landing as older history arrives. -describe('jumping from the rail while following the end', () => { - let restore: (() => void)[] = [] - let lastEventScrollTop = 0 - - beforeEach(() => { - vi.useFakeTimers({ - toFake: [ - 'Date', - 'performance', - 'setTimeout', - 'clearTimeout', - 'requestAnimationFrame', - 'cancelAnimationFrame' - ] - }) - const undoLayout = stubLayout({ scrollGeometry: true, offsetChain: true }) - const stubbedHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetHeight') - restore = [ - undoLayout, - stubResizeObserver(), - overrideLayoutProperty('offsetHeight', { - get(this: HTMLElement): number { - const estimated = - this.dataset.index === undefined ? undefined : ROW_HEIGHT_BY_TEXT.get(rowText(this)) - return estimated ?? stubbedHeight?.get?.call(this) ?? 0 - } - }), - // The rail stands down in a narrow pane. - overrideLayoutProperty('clientWidth', { get: () => 800 }), - // Rows sit at their `top` inside the spacer, which sits under the chrome. - overrideLayoutProperty('offsetTop', { - get(this: HTMLElement): number { - if (this.hasAttribute('data-native-chat-window')) { - return layout.aboveTranscriptPx - } - return this.dataset.index === undefined ? 0 : transcriptRowOffset(this) - } - }), - overrideLayoutProperty('offsetParent', { - get(this: HTMLElement): HTMLElement | null { - if (this.dataset.index !== undefined) { - return this.closest('[data-native-chat-window]') - } - return this.parentElement?.closest('[data-native-chat-scroll]') ?? null - } - }) - ] - // The older-history row counts only while it sits in the column's flow. - Object.defineProperty(layout, 'aboveTranscriptPx', { - configurable: true, - get: () => - transcriptWindowTop( - document.querySelector('[data-native-chat-window]'), - TOP_GUTTER_PX, - OLDER_HISTORY_ROW_PX - ) - }) - vi.spyOn(HTMLElement.prototype, 'scrollTo').mockImplementation(function scrollTo( - this: HTMLElement, - options?: ScrollToOptions | number - ): void { - if (typeof options === 'object' && options.top !== undefined) { - this.scrollTop = options.top - } - }) - lastEventScrollTop = 0 - }) - - afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() - Object.defineProperty(layout, 'aboveTranscriptPx', { - configurable: true, - writable: true, - value: 0 - }) - for (const undo of restore.toReversed()) { - undo() - } - }) - - function scroller(): HTMLElement { - const element = document.querySelector('[data-native-chat-scroll]') - if (!element) { - throw new Error('no transcript scroll root') - } - return element - } - - /** Deliver layout changes and scroll events before the virtualizer's next frame. */ - async function frame(): Promise { - const element = scroller() - act(() => { - // The stubbed setter clamps, so re-writing the offset applies a shrink. - const offset = element.scrollTop - element.scrollTop = offset - deliverResizes() - }) - if (element.scrollTop !== lastEventScrollTop) { - lastEventScrollTop = element.scrollTop - fireEvent.scroll(element) - } - await act(async () => { - vi.advanceTimersByTime(16) - }) - } - - async function settle(frames: number): Promise { - for (let index = 0; index < frames; index += 1) { - await frame() - } - } - - function distanceFromBottom(): number { - const element = scroller() - return element.scrollHeight - element.clientHeight - element.scrollTop - } - - function rowOffsetFromViewportTop(prompt: string): number { - const row = screen.getByText(prompt).closest('[data-index]') - if (!row) { - throw new Error(`${prompt} has no mounted row`) - } - return layout.aboveTranscriptPx + row.offsetTop - scroller().scrollTop - } - - it('lets a later pick of a loaded message win over a jump still paging', async () => { - let releaseFirstPage: (() => void) | null = null - let held = false - const holdPage = (): Promise => { - if (held) { - return Promise.resolve() - } - held = true - return new Promise((resolve) => { - releaseFirstPage = resolve - }) - } - render() - await settle(10) - - fireEvent.click(screen.getByRole('button', { name: 'prompt-5' })) - await frame() - expect(releaseFirstPage).not.toBeNull() - fireEvent.click(screen.getByRole('button', { name: 'prompt-45' })) - await settle(40) - act(() => releaseFirstPage?.()) - await settle(60) - - // The superseded jump would have kept paging and pulled the reader to prompt-5. - expect(screen.queryByText('prompt-5')).toBeNull() - expect(Math.abs(rowOffsetFromViewportTop('prompt-45'))).toBeLessThanOrEqual(2) - }) - /** Holds the first older page in flight until released; later pages land at once. */ - function holdFirstPage(): { - holdPage: () => Promise - release: () => void - asked: () => number - } { - let release: (() => void) | null = null - let asked = 0 - return { - holdPage: () => { - asked += 1 - return asked > 1 - ? Promise.resolve() - : new Promise((resolve) => { - release = resolve - }) - }, - release: () => act(() => release?.()), - asked: () => asked - } - } - - async function pickUnloadedWhilePaging(prompt: string): Promise { - fireEvent.click(screen.getByRole('button', { name: prompt })) - await frame() - } - - it.each([ - ['a wheel over the transcript', () => fireEvent.wheel(scroller(), { deltaY: -40 })], - ['a scroll key', () => fireEvent.keyDown(scroller(), { key: 'PageUp' })], - ['a touch drag', () => fireEvent.touchMove(scroller())], - ['a scrollbar grab', () => fireEvent.pointerDown(scroller())] - ])('leaves the reader where they are after %s while the jump pages', async (_case, input) => { - const pages = holdFirstPage() - render() - await settle(10) - await pickUnloadedWhilePaging('prompt-5') - expect(pages.asked()).toBe(1) - - expect(screen.getByRole('button', { name: 'prompt-5' }).getAttribute('aria-busy')).toBe('true') - - input() - await frame() - expect(screen.getByRole('button', { name: 'prompt-5' }).getAttribute('aria-busy')).toBeNull() - pages.release() - await settle(60) - - // The abandoned jump would have paged on and pulled the reader up to prompt-5. - expect(pages.asked()).toBe(1) - expect(screen.queryByText('prompt-5')).toBeNull() - expect(distanceFromBottom()).toBe(0) - }) - - it('stays at the latest message when "Jump to latest" is pressed while the jump pages', async () => { - const pages = holdFirstPage() - render() - await settle(10) - // A reader parked above the end, so the button shows. - act(() => { - fireEvent.wheel(scroller(), { deltaY: -100 }) - scroller().scrollTop = 200 - }) - await settle(2) - await pickUnloadedWhilePaging('prompt-5') - expect(pages.asked()).toBe(1) - - fireEvent.click(screen.getByRole('button', { name: 'Jump to latest' })) - await frame() - pages.release() - await settle(60) - - expect(pages.asked()).toBe(1) - expect(screen.queryByText('prompt-5')).toBeNull() - expect(distanceFromBottom()).toBe(0) - }) -}) diff --git a/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatMessageList.new-rows-marker.test.tsx b/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatMessageList.new-rows-marker.test.tsx index ca44f3e5740..1c07e35e353 100644 --- a/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatMessageList.new-rows-marker.test.tsx +++ b/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatMessageList.new-rows-marker.test.tsx @@ -84,16 +84,6 @@ describe('the "New" marker in the transcript', () => { expect(row?.dataset.index).toBe(String(TRANSCRIPT_LENGTH)) }) - it('tells a screen reader that new messages came, in a region that was already there', () => { - const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true)) - const region = container.querySelector('[data-native-chat-scroll] ~ [aria-live="polite"]') - expect(region).toBeEmptyDOMElement() - - rerender(chat(TRANSCRIPT_LENGTH, false)) - rerender(chat(TRANSCRIPT_LENGTH + 60, true)) - expect(region).toHaveTextContent('New messages arrived while you were away') - }) - it('is neither drawn nor announced when the reader turned it off', () => { const settings = useAppStore.getState().settings useAppStore.setState({ @@ -137,13 +127,6 @@ describe('the "New" marker in the transcript', () => { const scrollTop = (container: HTMLElement): number | undefined => container.querySelector('[data-native-chat-scroll]')?.scrollTop - it('brings a reader who was at the end to where the new rows begin', () => { - const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true)) - returnToNewRows(rerender) - - expect(scrollTop(container)).toBe(TRANSCRIPT_LENGTH * ROW_PITCH_PX) - }) - it('keeps the reader where the new rows begin while a reply is still being drawn', async () => { const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true)) returnToNewRows(rerender, 1) diff --git a/src/renderer/src/components/native-chat/viewport/new-rows/native-chat-new-rows-marker.test.tsx b/src/renderer/src/components/native-chat/viewport/new-rows/native-chat-new-rows-marker.test.tsx index 9616ca78887..855d5df2eed 100644 --- a/src/renderer/src/components/native-chat/viewport/new-rows/native-chat-new-rows-marker.test.tsx +++ b/src/renderer/src/components/native-chat/viewport/new-rows/native-chat-new-rows-marker.test.tsx @@ -66,13 +66,6 @@ const missed = (key: string, after: number, through: number) => ({ }) describe('where the "New" marker draws', () => { - it('is above the first row that came while the reader was away', () => { - expect(nativeChatNewRowsMarkerPlacement(slotsOf(LATER), missed('answer', 2, 4))).toEqual({ - key: 'answer', - place: 'above-row' - }) - }) - it("is above the turn bar when only that bar parts the row from the reader's prompt", () => { const asked = [row('prompt', 1, 'user'), row('answer', 2)] expect( @@ -100,11 +93,6 @@ describe('where the "New" marker draws', () => { ).toEqual({ key: 'step', place: 'above-row' }) } }) - - it('is absent when nothing came, or the row that did is gone', () => { - expect(nativeChatNewRowsMarkerPlacement(slotsOf(LATER), null)).toBeUndefined() - expect(nativeChatNewRowsMarkerPlacement(slotsOf(SEEN), missed('answer', 2, 4))).toBeUndefined() - }) }) describe('useNativeChatNewRowsMarker', () => { @@ -141,16 +129,6 @@ describe('useNativeChatNewRowsMarker', () => { return view } - it('marks nothing that arrives while the reader is looking', () => { - const view = chat(SEEN) - view.rerender({ messages: LATER, showing: true }) - expect(view.result.current.marker).toBeUndefined() - }) - - it('marks what a hidden chat is handed when the reader comes back to it', () => { - expect(leaveAndReturn(SEEN, LATER).result.current.marker?.key).toBe('answer') - }) - it("is never above the reader's own prompt", () => { const sent = [...SEEN, row('next-prompt', 3, 'user'), row('answer', 4)] expect(leaveAndReturn(SEEN, sent).result.current.marker?.key).toBe('answer') @@ -176,12 +154,6 @@ describe('useNativeChatNewRowsMarker', () => { expect(view.result.current.marker?.key).toBe('answer') }) - it('goes once the reader answers', () => { - const view = leaveAndReturn(SEEN, LATER) - act(() => view.result.current.dismiss()) - expect(view.result.current.marker).toBeUndefined() - }) - it('does not appear when the reader answered before the chat had caught up', () => { const view = chat(SEEN) view.rerender({ messages: SEEN, showing: false }) @@ -196,13 +168,6 @@ describe('useNativeChatNewRowsMarker', () => { expect(view.result.current.marker?.key).toBe('answer') }) - it('is arriving on the return, until the row that draws it has brought it into view', () => { - const view = leaveAndReturn(SEEN, LATER) - expect(view.result.current.marker?.arriving).toBe(true) - act(() => view.result.current.marker?.onArrived()) - expect(view.result.current.marker).toMatchObject({ key: 'answer', arriving: false }) - }) - it('stays where it is through another look away, until the reader answers', () => { const view = leaveAndReturn(SEEN, LATER) act(() => view.result.current.marker?.onArrived()) @@ -255,14 +220,6 @@ describe('useNativeChatNewRowsMarker', () => { expect(view.result.current.marker?.key).toBe('held') }) - it('keeps its place when the reader opens the turn that came while they were away', () => { - const view = leaveAndReturn(ASKED, DONE, { worked: 17 }) - expect(view.result.current.marker).toMatchObject({ key: 'prompt', place: 'above-turn-bar' }) - - view.rerender({ messages: DONE, showing: true, turn: { worked: 17, expanded: true } }) - expect(view.result.current.marker).toMatchObject({ key: 'prompt', place: 'above-turn-bar' }) - }) - it('stays through another look away after the reader shuts the turn they opened', () => { const shut = { worked: 17 } const view = leaveAndReturn(ASKED, DONE, { worked: 17, expanded: true }) @@ -278,14 +235,6 @@ describe('useNativeChatNewRowsMarker', () => { const marked = (onReturn: NativeChatMessage[]) => leaveAndReturn(begun, onReturn, { working: true }).result.current.marker?.key - it('is marked new when it grew while they were away', () => { - expect(marked(grown)).toBe('reply') - }) - - it('is not marked when it is as they left it', () => { - expect(marked(begun)).toBeUndefined() - }) - it('gives way to the next row when it is as they left it', () => { expect(marked([...begun, row('more', 3)])).toBe('more') }) diff --git a/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing.test.tsx b/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing.test.tsx deleted file mode 100644 index a3436b4ad22..00000000000 --- a/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing.test.tsx +++ /dev/null @@ -1,307 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' - -import { act, cleanup, fireEvent, screen } from '@testing-library/react' -import { render } from '../../messages/actions/native-chat-tooltip-test-harness' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -// Why: these fixtures have neither inline visual owners nor sender navigation. -const unusedChatLeaves = vi.hoisted(() => ({ - inlineVisual: vi.fn(() => { - throw new Error('Unexpected inline visual in transcript fixture') - }), - openSender: vi.fn(() => { - throw new Error('Unexpected sender navigation in transcript fixture') - }) -})) -vi.mock('../../media/visuals/NativeChatInlineVisual', () => ({ - NativeChatInlineVisual: unusedChatLeaves.inlineVisual -})) -vi.mock('@/lib/open-agent-message-sender', () => ({ - openAgentMessageSender: unusedChatLeaves.openSender -})) -import type { - AgentJournalItemBody, - AgentJournalRenderItem -} from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import { projectStructuredItemsToNativeChat } from '../../../../../../shared/agent-session/view/structured-agent-session-projection' -import { NativeChatMessageList } from '../../NativeChatMessageList' -import { NATIVE_CHAT_BOTTOM_THRESHOLD_PX } from '../scroll/native-chat-autoscroll' - -import { - deliverResizes, - list, - marker, - scrollTranscript, - session, - stubLayout, - stubResizeObserver, - TRANSCRIPT_LENGTH, - windowState -} from './native-chat-windowing-test-harness' - -afterEach(cleanup) - -function scrollRoot(container: HTMLElement): HTMLElement { - const scroller = container.querySelector('[data-native-chat-scroll]') - if (!scroller) { - throw new Error('no transcript scroll root') - } - return scroller -} - -/** Deliver resize and scroll events to a fixed point, as a painted frame would. */ -function paint(container: HTMLElement): void { - const scroller = scrollRoot(container) - let lastScrollTop = scroller.scrollTop - for (let pass = 0; pass < 12; pass += 1) { - let changed = false - act(() => { - changed = deliverResizes() - }) - if (scroller.scrollTop !== lastScrollTop) { - lastScrollTop = scroller.scrollTop - fireEvent.scroll(scroller) - changed = true - } - if (!changed) { - return - } - } - throw new Error('the transcript never settled: resize and scroll kept moving it') -} - -async function settleVirtualizer(container: HTMLElement): Promise { - for (let frame = 0; frame < 2; frame += 1) { - paint(container) - await act(async () => { - await new Promise((resolve) => requestAnimationFrame(() => resolve())) - }) - } - paint(container) -} - -describe('windowed transcript', () => { - let restoreLayout = (): void => {} - beforeEach(() => { - restoreLayout = stubLayout() - }) - afterEach(() => { - restoreLayout() - }) - - const transcript = Array.from({ length: TRANSCRIPT_LENGTH }, (_, index) => marker(index)) - - it('still has the tool run open when the row carrying it comes back', () => { - const withTool = [...transcript] - withTool[1] = { - ...marker(1), - blocks: [ - { type: 'text', text: 'marker-1' }, - { type: 'tool-call', name: 'shell', input: { command: 'ls' }, state: 'completed' } - ] - } - const { container } = render(list(withTool)) - - const header = screen.getByRole('button', { name: /^ls/ }) - expect(header).toHaveAttribute('aria-expanded', 'false') - fireEvent.click(header) - expect(screen.getByRole('button', { name: /^ls/ })).toHaveAttribute('aria-expanded', 'true') - - scrollTranscript(container, 5000) - expect(windowState(container).indexes).not.toContain(1) - expect(screen.queryByRole('button', { name: /^ls/ })).toBeNull() - - scrollTranscript(container, 0) - expect(screen.getByRole('button', { name: /^ls/ })).toHaveAttribute('aria-expanded', 'true') - }) -}) - -// Diff reveals name and pin an earlier, possibly unmounted message until its card can answer. -describe('revealing a diff from a turn rollup', () => { - let restoreLayout = (): void => {} - beforeEach(() => { - restoreLayout = stubLayout() - }) - afterEach(() => { - restoreLayout() - vi.restoreAllMocks() - }) - - function journalItem(itemId: string, body: AgentJournalItemBody, sequence: number) { - return { itemId, body, sequence, observedAt: sequence * 1000, revision: 1 } - } - - const patch = '@@ -1 +1 @@\n-before\n+after' - const items: AgentJournalRenderItem[] = [ - journalItem( - 'user', - { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Edit it' }] }, - 1 - ), - journalItem( - 'diff', - { - kind: 'diff', - path: 'src/a.ts', - patch: { head: patch, truncated: false, digest: 'fixture', byteLength: patch.length } - }, - 2 - ), - ...Array.from({ length: TRANSCRIPT_LENGTH }, (_, index) => - journalItem( - `tail-${index}`, - { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: `marker-${index}` }] }, - index + 3 - ) - ) - ] - - it('opens an old edit inline at the visible turn outcome without mounting its source row', () => { - const scrollTo = vi.fn() - vi.spyOn(HTMLElement.prototype, 'scrollTo').mockImplementation(scrollTo) - const { container } = render( - - ) - // The pinned tail holds the rollup; its target diff has scrolled out of the window. - scrollTranscript(container, 4000) - expect(screen.queryByRole('button', { name: /^Edited .*a\.ts(?:\s|$)/ })).toBeNull() - - scrollTo.mockClear() - fireEvent.click(screen.getByRole('button', { name: /src\/a.ts/ })) - - expect(screen.getByText('Edited')).toBeInTheDocument() - expect(screen.getByText('after')).toBeInTheDocument() - expect(scrollTo).not.toHaveBeenCalled() - }) -}) - -describe('transcript with a hidden scroll root', () => { - it('preserves a detached viewport when messages append while hidden', async () => { - let isVisible = true - const restoreLayout = stubLayout({ - scrollGeometry: true, - isVisible: () => isVisible - }) - const restoreResizeObserver = stubResizeObserver() - const initialMessages = Array.from({ length: 120 }, (_, index) => marker(index)) - const appendedMessages = [ - ...initialMessages, - ...Array.from({ length: 20 }, (_, index) => marker(120 + index)) - ] - try { - const { container, rerender } = render(list(initialMessages, isVisible)) - await settleVirtualizer(container) - - const scroller = scrollRoot(container) - const readingAt = 2_000 - scrollTranscript(container, readingAt) - await settleVirtualizer(container) - expect(screen.getByRole('button', { name: /jump to latest/i })).toBeInTheDocument() - - isVisible = false - rerender(list(initialMessages, isVisible)) - await settleVirtualizer(container) - const scrollTo = vi.spyOn(scroller, 'scrollTo') - try { - rerender(list(appendedMessages, isVisible)) - await settleVirtualizer(container) - expect(scrollTo).not.toHaveBeenCalled() - } finally { - scrollTo.mockRestore() - } - - isVisible = true - rerender(list(appendedMessages, isVisible)) - await settleVirtualizer(container) - - expect(scroller.scrollTop).toBe(readingAt) - expect(screen.getByRole('button', { name: /jump to latest/i })).toBeInTheDocument() - } finally { - restoreResizeObserver() - restoreLayout() - } - }) - - it('preserves a detached viewport when a structured session catches up after reveal', async () => { - let isVisible = true - const restoreLayout = stubLayout({ - scrollGeometry: true, - isVisible: () => isVisible - }) - const restoreResizeObserver = stubResizeObserver() - const initialMessages = Array.from({ length: 120 }, (_, index) => marker(index)) - const appendedMessages = [ - ...initialMessages, - ...Array.from({ length: 20 }, (_, index) => marker(120 + index)) - ] - try { - const { container, rerender } = render(list(initialMessages, isVisible)) - await settleVirtualizer(container) - - const scroller = scrollRoot(container) - const readingAt = 2_000 - scrollTranscript(container, readingAt) - await settleVirtualizer(container) - expect(screen.getByRole('button', { name: /jump to latest/i })).toBeInTheDocument() - - isVisible = false - rerender(list(initialMessages, isVisible)) - await settleVirtualizer(container) - isVisible = true - rerender(list(initialMessages, isVisible)) - // The resumed transport can publish catch-up before the reveal write emits a scroll event. - rerender(list(appendedMessages, isVisible)) - await settleVirtualizer(container) - - expect(scroller.scrollTop).toBe(readingAt) - expect(screen.getByRole('button', { name: /jump to latest/i })).toBeInTheDocument() - } finally { - restoreResizeObserver() - restoreLayout() - } - }) - - it('catches a following viewport up after messages append while hidden', async () => { - let isVisible = true - const restoreLayout = stubLayout({ - scrollGeometry: true, - isVisible: () => isVisible - }) - const restoreResizeObserver = stubResizeObserver() - const initialMessages = Array.from({ length: 120 }, (_, index) => marker(index)) - const appendedMessages = [ - ...initialMessages, - ...Array.from({ length: 20 }, (_, index) => marker(120 + index)) - ] - try { - const { container, rerender } = render(list(initialMessages, isVisible)) - await settleVirtualizer(container) - - isVisible = false - rerender(list(initialMessages, isVisible)) - await settleVirtualizer(container) - rerender(list(appendedMessages, isVisible)) - await settleVirtualizer(container) - - isVisible = true - rerender(list(appendedMessages, isVisible)) - await settleVirtualizer(container) - - const scroller = scrollRoot(container) - expect( - scroller.scrollHeight - scroller.clientHeight - scroller.scrollTop - ).toBeLessThanOrEqual(NATIVE_CHAT_BOTTOM_THRESHOLD_PX) - expect(screen.queryByRole('button', { name: /jump to latest/i })).toBeNull() - } finally { - restoreResizeObserver() - restoreLayout() - } - }) -}) diff --git a/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.tsx b/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.tsx index 934872dfaed..2606c2dd035 100644 --- a/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.tsx +++ b/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.tsx @@ -13,7 +13,7 @@ import { getIndexedWorktreeById, getIndexedWorktreeMap } from '@/store/slices/worktrees/listing/worktree-catalog-index' -import { compareWorktreeDisplayName } from '@/lib/worktree-display-name-order' +import { compareWorktreeDisplayName } from '@/lib/workspace/display/worktree-display-name-order' import '@/components/sidebar/workspace-card/activity/worktree-card-empty-inputs' import { branchDisplayName } from '@/components/sidebar/workspace-card/identity/worktree-branch-display' import { getCyclicProjectedWorktreeLineageIds } from '../../../../shared/sidebar-list/worktree-lineage-projection' diff --git a/src/renderer/src/components/new-workspace/smart-workspace-name-input-surface.tsx b/src/renderer/src/components/new-workspace/smart-workspace-name-input-surface.tsx index 6478924fcbd..9158baa9aa1 100644 --- a/src/renderer/src/components/new-workspace/smart-workspace-name-input-surface.tsx +++ b/src/renderer/src/components/new-workspace/smart-workspace-name-input-surface.tsx @@ -8,7 +8,7 @@ import { isImeCompositionKeyDown } from '@/lib/text-input/ime/ime-composition-ke import { isBlockingJiraUrlIntent } from '../../../../shared/new-workspace/smart-workspace-source-results' import { isBlockingLinearUrlIntent } from '../../../../shared/new-workspace/smart-workspace-linear-intent' import { isComposerFieldToFieldFocus } from './smart-workspace-source-popover-focus' -import { replaceCompletedWorkspaceEmojiShortcode } from '@/lib/workspace-emoji-shortcodes' +import { replaceCompletedWorkspaceEmojiShortcode } from '@/lib/workspace/display/workspace-emoji-shortcodes' import { cn } from '@/lib/class-names' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-actions.ts b/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-actions.ts index 47db3fb4ae4..5b5c1ab4dea 100644 --- a/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-actions.ts +++ b/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-actions.ts @@ -6,9 +6,9 @@ import { lookupGitHubWorkItemByOwnerRepoForSource } from '@/lib/work-items/githu import { applyWorkspaceEmojiSuggestion, type WorkspaceEmojiReplacement, - type getActiveWorkspaceEmojiShortcode, - type WorkspaceEmojiSuggestion -} from '@/lib/workspace-emoji-shortcodes' + type getActiveWorkspaceEmojiShortcode +} from '@/lib/workspace/display/workspace-emoji-shortcodes' +import type { StandardEmojiShortcodeEntry } from '../../../../shared/emoji-shortcode-catalog' import type { GitHubWorkItem } from '../../../../shared/github/work-item-types' import { buildTaskSourceContextFromRepo } from '../../../../shared/work-items/task-source-context' import type { @@ -19,7 +19,7 @@ import type { import { getRepoSlugCached, sameSlug } from './smart-workspace-repo-slug' import type { useWorkItemSourceSearch } from './use-work-item-source-search' import type { useSmartWorkspaceFieldFocusControls } from './use-smart-workspace-field-focus-controls' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import type { useWorkItemSourcePresentation } from './use-work-item-source-presentation' import { openAppHttpLink } from '@/lib/browser/navigation/app-http-link-open' @@ -139,7 +139,7 @@ export function useSmartWorkspaceNameFieldActions( ] ) const handleEmojiSelect = useCallback( - (suggestion: WorkspaceEmojiSuggestion): void => { + (suggestion: StandardEmojiShortcodeEntry): void => { if (!activeEmojiShortcode) { return } diff --git a/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-controller.ts b/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-controller.ts index 02eeeeaf5ee..5c5e8e7967c 100644 --- a/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-controller.ts +++ b/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-controller.ts @@ -1,9 +1,9 @@ import { useEffect, useMemo } from 'react' import { getActiveWorkspaceEmojiShortcode, - searchWorkspaceEmojiShortcodes, - type WorkspaceEmojiSuggestion -} from '@/lib/workspace-emoji-shortcodes' + searchWorkspaceEmojiShortcodes +} from '@/lib/workspace/display/workspace-emoji-shortcodes' +import type { StandardEmojiShortcodeEntry } from '../../../../shared/emoji-shortcode-catalog' import type { SmartWorkspaceNameFieldProps } from './smart-workspace-name-field-model' import { useWorkItemSourceSearch } from './use-work-item-source-search' import { useSmartWorkspaceFieldFocusControls } from './use-smart-workspace-field-focus-controls' @@ -38,7 +38,7 @@ export function useSmartWorkspaceNameFieldController(props: SmartWorkspaceNameFi () => getActiveWorkspaceEmojiShortcode(value, emojiCursor), [emojiCursor, value] ) - const emojiSuggestions: WorkspaceEmojiSuggestion[] = useMemo( + const emojiSuggestions: StandardEmojiShortcodeEntry[] = useMemo( () => (activeEmojiShortcode ? searchWorkspaceEmojiShortcodes(activeEmojiShortcode.query) : []), [activeEmojiShortcode] ) diff --git a/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-foundation.source.test.tsx b/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-foundation.source.test.tsx index 0c11b0d2d66..e1900287378 100644 --- a/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-foundation.source.test.tsx +++ b/src/renderer/src/components/new-workspace/use-smart-workspace-name-field-foundation.source.test.tsx @@ -1,16 +1,13 @@ import { linearIssueReadFixture } from '@/store/slices/linear/linear-slice-test-harness' -// @vitest-environment happy-dom - import { act, cleanup, renderHook, waitFor } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../../shared/repo-types' - -import type { LinearIssue } from '../../../../shared/linear/issue-types' - -import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' -import type { NormalizedWorkItemSourceSearchProps } from './smart-workspace-name-field-model' import { useWorkItemSourceSearch } from './use-work-item-source-search' import { referenceLinearIssue } from '../sidebar/workspace-card/review/workspace-reference-fixtures.test-support' +import type { Repo } from '../../../../shared/repo-types' +import type { LinearIssue } from '../../../../shared/linear/issue-types' +import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' +import type { NormalizedWorkItemSourceSearchProps } from './smart-workspace-name-field-model' +// @vitest-environment happy-dom const mocks = vi.hoisted(() => ({ readStatus: vi.fn(), @@ -38,7 +35,7 @@ vi.mock('@/lib/work-items/gitlab/gitlab-work-item-source-lookup', () => ({ listGitLabWorkItemsForSource: mocks.listGitlabWorkItems, lookupGitLabWorkItemByPathForSource: vi.fn() })) -vi.mock('@/store', () => ({ +vi.mock('@/store/index', () => ({ useAppStore: Object.assign( (selector: (state: unknown) => unknown) => selector({ @@ -51,8 +48,11 @@ vi.mock('@/store', () => ({ { getState: () => mocks.state, subscribe: () => () => {} } ) })) -vi.mock('@/lib/local-preflight-context', () => ({ - getLocalPreflightContext: () => ({}), +vi.mock('@/runtime/hosts/preflight/local-preflight-context', () => ({ + getLocalPreflightContext: () => ({}) +})) + +vi.mock('@/runtime/hosts/preflight/local-preflight-context-key', () => ({ localPreflightContextKey: () => 'test' })) vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) diff --git a/src/renderer/src/components/new-workspace/use-work-item-source-foundation.ts b/src/renderer/src/components/new-workspace/use-work-item-source-foundation.ts index ce08bb48e6f..667e097bae2 100644 --- a/src/renderer/src/components/new-workspace/use-work-item-source-foundation.ts +++ b/src/renderer/src/components/new-workspace/use-work-item-source-foundation.ts @@ -1,22 +1,15 @@ -import type { LinearIssueData } from '@/store/slices/linear/linear-issue-read' -import type { LinearIssueView } from '@/store/slices/linear/linear-issue-read-lifecycle' import { getProviderRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context' import { useLinearIssueResult } from '@/hooks/linear-issue-committed-state' import { getLinearSourceScope } from '@/store/slices/linear/linear-slice-scope' import { getSelectedWorkspaceId } from '@/store/slices/linear/linear-cache' import { defaultScopeSource } from '@/runtime/hosts/selection/default-creation-host' -import type { LinearIssue } from '../../../../shared/linear/issue-types' import { parseBoundedSmartWorkspaceLinearIssueUrlIntent } from '../../../../shared/new-workspace/smart-workspace-linear-intent' import { isSmartWorkspaceSourceQueryWithinLimit } from '../../../../shared/new-workspace/smart-workspace-source-results' import React, { useMemo } from 'react' import { useShallow } from 'zustand/react/shallow' -import { useAppStore } from '@/store' -import { getLocalPreflightContext, localPreflightContextKey } from '@/lib/local-preflight-context' +import { useAppStore } from '@/store/index' +import { getLocalPreflightContext } from '@/runtime/hosts/preflight/local-preflight-context' import { buildTaskSourceContextFromRepo } from '../../../../shared/work-items/task-source-context' -import type { - NormalizedWorkItemSourceSearchProps, - RepoBackedSearchTarget -} from './smart-workspace-name-field-model' import { useJiraSourceConnection } from './use-jira-source-connection' import { useJiraUrlSource } from './use-jira-url-source' import { useLinearSourceConnection } from './use-linear-source-connection' @@ -24,6 +17,14 @@ import { useSmartWorkspaceFieldAvailability } from './use-smart-workspace-field- import { useWorkItemSourceState } from './use-work-item-source-state' import { useJiraComposerProject } from './use-jira-composer-project' import { useComposerSourceScope } from './use-composer-source-scope' +import type { LinearIssueData } from '@/store/slices/linear/linear-issue-read' +import type { LinearIssueView } from '@/store/slices/linear/linear-issue-read-lifecycle' +import type { LinearIssue } from '../../../../shared/linear/issue-types' +import { localPreflightContextKey } from '../../runtime/hosts/preflight/local-preflight-context-key' +import type { + NormalizedWorkItemSourceSearchProps, + RepoBackedSearchTarget +} from './smart-workspace-name-field-model' export function useWorkItemSourceFoundation(props: NormalizedWorkItemSourceSearchProps) { const { diff --git a/src/renderer/src/lib/notes-send-in-flight.ts b/src/renderer/src/components/notes/delivery/notes-send-in-flight.ts similarity index 100% rename from src/renderer/src/lib/notes-send-in-flight.ts rename to src/renderer/src/components/notes/delivery/notes-send-in-flight.ts diff --git a/src/renderer/src/components/onboarding/ThemeStep.tsx b/src/renderer/src/components/onboarding/ThemeStep.tsx index aceb72b7cd3..10e81b5f9ba 100644 --- a/src/renderer/src/components/onboarding/ThemeStep.tsx +++ b/src/renderer/src/components/onboarding/ThemeStep.tsx @@ -5,21 +5,19 @@ import { toast } from 'sonner' import { track } from '@/diagnostics/telemetry/telemetry' import { useMountedRef } from '@/hooks/useMountedRef' import { GhosttyDiscoveryRow } from './GhosttyDiscoveryRow' -import type { GlobalSettings } from '../../../../shared/global-settings-types' -import type { DiscoveryStatusEmitted } from '../../../../shared/onboarding-state-types' import { i18n, translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' import { ThemeSlotControl, useThemeLooks } from './ThemeLookGallery' import { ThemeLookCarousel, openThemePluginDirectory } from './ThemeLookCarousel' import { ThemeModeTiles } from './ThemeModeTiles' -import type { ThemeLook, ThemeLookBase } from './onboarding-theme-looks' import { themeLookSettingsUpdate } from './onboarding-theme-look-settings' -import { - terminalConfigImportSettingsUpdate, - type TerminalConfigImportPreview -} from '../../../../shared/terminal/appearance/terminal-config-import-preview' -import { getSystemPrefersDark } from '@/lib/terminal-theme' +import { terminalConfigImportSettingsUpdate } from '../../../../shared/terminal/appearance/terminal-config-import-preview' +import type { TerminalConfigImportPreview } from '../../../../shared/terminal/appearance/terminal-config-import-preview' +import { getSystemPrefersDark } from '@/lib/terminal/appearance/terminal-theme' import { useSystemPrefersDark } from '@/hooks/theme/use-system-prefers-dark' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import type { DiscoveryStatusEmitted } from '../../../../shared/onboarding-state-types' +import type { ThemeLook, ThemeLookBase } from './onboarding-theme-looks' type ThemeStepProps = { theme: GlobalSettings['theme'] diff --git a/src/renderer/src/components/onboarding/onboarding-feature-setup.test.ts b/src/renderer/src/components/onboarding/onboarding-feature-setup.test.ts deleted file mode 100644 index 0c32da19e6f..00000000000 --- a/src/renderer/src/components/onboarding/onboarding-feature-setup.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { - ComputerUsePermissionSetupResult, - ComputerUsePermissionStatusResult -} from '../../../../shared/computer-use-permissions-types' -import { ORCHESTRATION_SKILL_NAME } from '@/lib/skills/installation/agent-feature-skill-names' -import { BROWSER_USE_ENABLED_STORAGE_KEY } from '@/lib/browser/browser-use-setup-state' -import { ORCHESTRATION_ENABLED_STORAGE_KEY } from '@/lib/orchestration-setup-state' -import { - runOnboardingFeatureSetup, - type OnboardingFeatureSetupDeps, - type OnboardingFeatureSetupSelection -} from './onboarding-feature-setup' - -const GRANTED_COMPUTER_USE_STATUS: ComputerUsePermissionStatusResult = { - platform: 'darwin', - helperAppPath: '/Applications/Orca Computer Use.app', - helperUnavailableReason: null, - permissions: [ - { id: 'accessibility', status: 'granted' }, - { id: 'screenshots', status: 'granted' } - ] -} - -const OPENED_COMPUTER_USE_SETUP: ComputerUsePermissionSetupResult = { - platform: 'darwin', - helperAppPath: '/Applications/Orca.app', - openedSettings: true, - launchedHelper: true -} - -function createDeps( - overrides: Partial = {} -): OnboardingFeatureSetupDeps & { - storage: Map -} { - const storage = new Map() - return { - storage, - getComputerUsePermissionStatus: vi.fn(async () => GRANTED_COMPUTER_USE_STATUS), - openComputerUsePermissionSetup: vi.fn(async () => OPENED_COMPUTER_USE_SETUP), - setStorageItem: vi.fn((key: string, value: string) => { - storage.set(key, value) - }), - removeStorageItem: vi.fn((key: string) => { - storage.delete(key) - }), - notifyOrchestrationStateChanged: vi.fn(), - ...overrides - } -} - -describe('onboarding feature setup runner', () => { - afterEach(() => { - vi.unstubAllGlobals() - }) - - it('keeps invasive Browser Use and Computer Use setup untouched when only Orchestration is selected', async () => { - const deps = createDeps() - const selection: OnboardingFeatureSetupSelection = { - browserUse: false, - computerUse: false, - orchestration: true, - linearTickets: false - } - - const result = await runOnboardingFeatureSetup(selection, deps) - - expect(result.selectedIds).toEqual(['orchestration']) - expect(result.skillNames).toEqual([ORCHESTRATION_SKILL_NAME]) - expect(result.computerUsePermissionsOpened).toBe(false) - expect(deps.getComputerUsePermissionStatus).not.toHaveBeenCalled() - expect(deps.openComputerUsePermissionSetup).not.toHaveBeenCalled() - expect(deps.storage.get(BROWSER_USE_ENABLED_STORAGE_KEY)).toBe('0') - expect(deps.storage.get(ORCHESTRATION_ENABLED_STORAGE_KEY)).toBe('1') - }) - - it('keeps main’s skill selection but skips permissions when the Computer Use helper is unavailable', async () => { - // Missing helpers report every permission ungranted; do not call openSetup, which would throw. - const unavailableStatus: ComputerUsePermissionStatusResult = { - platform: 'darwin', - helperAppPath: null, - helperUnavailableReason: 'Orca Computer Use.app was not found', - permissions: [ - { id: 'accessibility', status: 'not-granted' }, - { id: 'screenshots', status: 'not-granted' } - ] - } - const openComputerUsePermissionSetup = vi.fn(async () => OPENED_COMPUTER_USE_SETUP) - const deps = createDeps({ - getComputerUsePermissionStatus: vi.fn(async () => unavailableStatus), - openComputerUsePermissionSetup - }) - - const result = await runOnboardingFeatureSetup( - { browserUse: true, computerUse: true, orchestration: true, linearTickets: true }, - deps - ) - - expect(result.skillNames).toEqual([ - 'orca-cli', - 'orca-computer-use', - 'orchestration', - 'orca-linear' - ]) - expect(result.computerUsePermissionsOpened).toBe(false) - expect(openComputerUsePermissionSetup).not.toHaveBeenCalled() - expect(result.warnings).toContainEqual({ - featureId: 'computerUse', - message: 'Orca Computer Use.app was not found' - }) - }) -}) diff --git a/src/renderer/src/components/onboarding/onboarding-feature-setup.ts b/src/renderer/src/components/onboarding/onboarding-feature-setup.ts index c0a5edb7604..35751f6c3aa 100644 --- a/src/renderer/src/components/onboarding/onboarding-feature-setup.ts +++ b/src/renderer/src/components/onboarding/onboarding-feature-setup.ts @@ -14,7 +14,7 @@ import { ORCHESTRATION_ENABLED_STORAGE_KEY, ORCHESTRATION_SETUP_DISMISSED_STORAGE_KEY, notifyOrchestrationSetupStateChanged -} from '@/lib/orchestration-setup-state' +} from '@/components/orchestration/setup/orchestration-setup-state' import type { EventProps } from '../../../../shared/telemetry-event-classification' import type { BundledSkillInstallState } from '@/hooks/skills/installation/use-bundled-skill-install' diff --git a/src/renderer/src/components/onboarding/onboarding-theme-look-settings.ts b/src/renderer/src/components/onboarding/onboarding-theme-look-settings.ts index 5b9dc1088da..2ac3833b44e 100644 --- a/src/renderer/src/components/onboarding/onboarding-theme-look-settings.ts +++ b/src/renderer/src/components/onboarding/onboarding-theme-look-settings.ts @@ -8,7 +8,7 @@ import { hasTerminalColorOverrides, TERMINAL_COLOR_OVERRIDES_SETTING } from '../../../../shared/terminal-themes/terminal-color-overrides' -import { withTerminalPluginPalettes } from '@/lib/terminal-plugin-palettes' +import { withTerminalPluginPalettes } from '@/lib/terminal/themes/terminal-plugin-palettes' import { terminalThemeUpdate } from '../plugins/state/plugin-theme-apply' import { builtInThemeLookId, type ThemeLook, type ThemeLookBase } from './onboarding-theme-looks' diff --git a/src/renderer/src/components/orchestration-crew/CrewAgentIcons.tsx b/src/renderer/src/components/orchestration-crew/CrewAgentIcons.tsx index 3b3e6d9c8a1..02d82401083 100644 --- a/src/renderer/src/components/orchestration-crew/CrewAgentIcons.tsx +++ b/src/renderer/src/components/orchestration-crew/CrewAgentIcons.tsx @@ -5,7 +5,7 @@ import { AgentTypeIcon } from '@/components/agent/icons/agent-type-icon' import { cn } from '@/lib/class-names' import { getAgentLabel } from '@/lib/agent-catalog/agent-catalog' import { mapAgentStatusStateToVisualStatus } from '@/lib/agent-status/aggregation/worktree-agent-status' -import { getWorktreeStatusLabel } from '@/lib/worktree-status' +import { getWorktreeStatusLabel } from '@/lib/workspace/activity/worktree-status' import type { WorktreeStatus } from '../../../../shared/worktree-status-rollup' import { useAgentMessageSenderViews, diff --git a/src/renderer/src/components/orchestration-crew/CrewRowView.tsx b/src/renderer/src/components/orchestration-crew/CrewRowView.tsx index 9655e6d0087..0b9644e8ff7 100644 --- a/src/renderer/src/components/orchestration-crew/CrewRowView.tsx +++ b/src/renderer/src/components/orchestration-crew/CrewRowView.tsx @@ -2,15 +2,16 @@ import { memo } from 'react' import { ChevronDown, ChevronRight, ExternalLink } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { openOrchestrationCrewAgent } from '@/lib/open-agent-message-sender' +import { openOrchestrationCrewAgent } from '@/lib/agent-session/open/open-agent-message-sender' import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' -import type { OrchestrationCrewRow } from '../../../../shared/orchestration/orchestration-crew' -import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' import { CrewRowDetails, CrewRowTime as Time } from './CrewRowDetails' import { CrewRowMenu } from './CrewRowMenu' -import { CrewAgentIcons, type CrewRowLook } from './CrewAgentIcons' +import { CrewAgentIcons } from './CrewAgentIcons' +import type { CrewRowLook } from './CrewAgentIcons' +import type { OrchestrationCrewRow } from '../../../../shared/orchestration/orchestration-crew' +import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' export function IconButton({ label, diff --git a/src/renderer/src/lib/orchestration-setup-state.ts b/src/renderer/src/components/orchestration/setup/orchestration-setup-state.ts similarity index 89% rename from src/renderer/src/lib/orchestration-setup-state.ts rename to src/renderer/src/components/orchestration/setup/orchestration-setup-state.ts index 6dcc6c418da..8b457c7dd1a 100644 --- a/src/renderer/src/lib/orchestration-setup-state.ts +++ b/src/renderer/src/components/orchestration/setup/orchestration-setup-state.ts @@ -6,10 +6,6 @@ export function isOrchestrationSetupEnabled(): boolean { return localStorage.getItem(ORCHESTRATION_ENABLED_STORAGE_KEY) === '1' } -export function hasOrchestrationSetupMarker(): boolean { - return isOrchestrationSetupEnabled() -} - export function markOrchestrationSetupComplete(): void { localStorage.setItem(ORCHESTRATION_ENABLED_STORAGE_KEY, '1') notifyOrchestrationSetupStateChanged() diff --git a/src/renderer/src/lib/orchestration-usage-examples.ts b/src/renderer/src/components/orchestration/setup/orchestration-usage-examples.ts similarity index 96% rename from src/renderer/src/lib/orchestration-usage-examples.ts rename to src/renderer/src/components/orchestration/setup/orchestration-usage-examples.ts index 626e7015de5..f0a8da06e82 100644 --- a/src/renderer/src/lib/orchestration-usage-examples.ts +++ b/src/renderer/src/components/orchestration/setup/orchestration-usage-examples.ts @@ -1,6 +1,6 @@ import { translate } from '@/i18n/i18n' import { createLocalizedCatalog } from '@/i18n/localized-catalog' -import type { SkillUsageExample } from './skills/examples/skill-usage-example' +import type { SkillUsageExample } from '../../../lib/skills/examples/skill-usage-example' export const getOrchestrationUsageExamples = createLocalizedCatalog((): SkillUsageExample[] => [ { diff --git a/src/renderer/src/components/plain-ssh-terminal/PlainSshTerminalView.tsx b/src/renderer/src/components/plain-ssh-terminal/PlainSshTerminalView.tsx index 3741f3a20a8..76d6fe4c6bc 100644 --- a/src/renderer/src/components/plain-ssh-terminal/PlainSshTerminalView.tsx +++ b/src/renderer/src/components/plain-ssh-terminal/PlainSshTerminalView.tsx @@ -1,17 +1,11 @@ import { useEffect, useLayoutEffect, useRef } from 'react' import { FitAddon } from '@xterm/addon-fit' -import type { ITheme, Terminal } from '@xterm/xterm' -import type { GlobalSettings } from '../../../../shared/global-settings-types' -import type { - PlainSshTerminalEvent, - PlainSshTerminalOpenResult -} from '../../../../shared/plain-ssh-terminal' import { TerminalKittyKeyboardModeTracker } from '../../../../shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker' import { translate } from '@/i18n/i18n' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { useEffectiveMacOptionAsAlt } from '@/lib/keyboard-layout/use-effective-mac-option-as-alt' import { composeActiveTerminalTheme } from '@/components/terminal-pane/appearance/terminal-appearance' -import { resolveEffectiveTerminalAppearance } from '@/lib/terminal-theme' +import { resolveEffectiveTerminalAppearance } from '@/lib/terminal/appearance/terminal-theme' import { useSystemPrefersDark } from '@/hooks/theme/use-system-prefers-dark' import { resolveTerminalMinimumContrastRatio } from '../../../../shared/terminal-themes/terminal-contrast-correction' import { syncPreviewTerminalLigatures } from '@/components/dashboard-popout/preview-terminal-ligatures' @@ -22,6 +16,12 @@ import { import { openStandaloneTerminal } from '@/components/standalone-terminal/open-standalone-terminal' import { removePlainSshPanel } from '@/ssh/plain-ssh-terminal-panels' import { usePluginFontReady } from '@/store/plugins/appearance/plugin-fonts' +import type { ITheme, Terminal } from '@xterm/xterm' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import type { + PlainSshTerminalEvent, + PlainSshTerminalOpenResult +} from '../../../../shared/plain-ssh-terminal' export type PlainSshTerminalPhase = | { kind: 'opening' } diff --git a/src/renderer/src/components/plugins/catalog/PluginCatalogGroups.tsx b/src/renderer/src/components/plugins/catalog/PluginCatalogGroups.tsx index 8a92e8610db..0331db71371 100644 --- a/src/renderer/src/components/plugins/catalog/PluginCatalogGroups.tsx +++ b/src/renderer/src/components/plugins/catalog/PluginCatalogGroups.tsx @@ -2,7 +2,7 @@ import { AlertTriangle, CircleAlert } from 'lucide-react' import type { PluginMarketplaceHostSourceState } from '../../../../../preload/api-types' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { formatShortTimeAgo } from '@/lib/short-time-ago' +import { formatShortTimeAgo } from '@/lib/time-format/short-time-ago' import { Button } from '../../ui/button' import { PluginListGroup } from '../list/PluginListGroup' import type { PluginListEntry } from '../list/plugin-list-entries' diff --git a/src/renderer/src/components/plugins/page/PluginContributionActionCommand.tsx b/src/renderer/src/components/plugins/page/PluginContributionActionCommand.tsx index 8030b0da02c..058b1547891 100644 --- a/src/renderer/src/components/plugins/page/PluginContributionActionCommand.tsx +++ b/src/renderer/src/components/plugins/page/PluginContributionActionCommand.tsx @@ -2,8 +2,8 @@ import { useState } from 'react' import { flushSync } from 'react-dom' import { toast } from 'sonner' import { useTranslate } from '@/i18n/use-translate' -import { executePluginCommand } from '@/lib/plugin-command-execution' -import { useAppStore } from '@/store' +import { executePluginCommand } from '@/lib/plugins/commands/plugin-command-execution' +import { useAppStore } from '@/store/index' import type { ActivePluginCommand } from '@/store/plugins/catalog/plugin-contribution-catalog' import { Button } from '../../ui/button' diff --git a/src/renderer/src/components/plugins/page/plugin-contribution-action-availability.ts b/src/renderer/src/components/plugins/page/plugin-contribution-action-availability.ts index d9b24751663..fca72c65538 100644 --- a/src/renderer/src/components/plugins/page/plugin-contribution-action-availability.ts +++ b/src/renderer/src/components/plugins/page/plugin-contribution-action-availability.ts @@ -2,7 +2,7 @@ import type { PluginHostListEntry } from '../../../../../preload/api-types' import { isWorkspaceScopedPluginContext } from '../../../../../shared/plugins/contributions/plugin-command-contribution' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' -import { canShowRightSidebarForView } from '@/lib/right-sidebar-visibility' +import { canShowRightSidebarForView } from '@/components/right-sidebar/visibility/right-sidebar-visibility' import type { AppState } from '@/store/types' /** Only these statuses back the Adds rows with Orca's live registrations, so a "try it" does what it says. */ diff --git a/src/renderer/src/components/plugins/state/plugin-theme-apply.ts b/src/renderer/src/components/plugins/state/plugin-theme-apply.ts index edcc5bcb0e9..9fe4048835f 100644 --- a/src/renderer/src/components/plugins/state/plugin-theme-apply.ts +++ b/src/renderer/src/components/plugins/state/plugin-theme-apply.ts @@ -1,7 +1,4 @@ import { toast } from 'sonner' -import type { GlobalSettings } from '../../../../../shared/global-settings-types' -import type { PluginThemeRegistration } from '../../../../../shared/plugins/artifacts/plugin-theme-artifact' -import type { PluginTerminalThemeRegistration } from '../../../../../shared/plugins/artifacts/plugin-terminal-theme-artifact' import { translate } from '@/i18n/i18n' import { resolveDocumentTheme } from '@/app-shell/appearance/document-theme' import { pluginAppThemeSlotUpdate } from '../../../../../shared/plugin-theme-settings' @@ -9,19 +6,20 @@ import { hasTerminalColorOverrides, TERMINAL_COLOR_OVERRIDES_SETTING } from '../../../../../shared/terminal-themes/terminal-color-overrides' -import { withTerminalPluginPalettes } from '@/lib/terminal-plugin-palettes' -import { BUILTIN_TERMINAL_THEME_NAMES } from '@/lib/terminal-theme' -import { - disambiguatedPluginContentLabels, - type PluginContentLabelItem -} from '../presentation/plugin-name-disambiguation' -import { useAppStore } from '@/store' +import { withTerminalPluginPalettes } from '@/lib/terminal/themes/terminal-plugin-palettes' +import { BUILTIN_TERMINAL_THEME_NAMES } from '@/lib/terminal/appearance/terminal-theme' +import { disambiguatedPluginContentLabels } from '../presentation/plugin-name-disambiguation' +import type { PluginContentLabelItem } from '../presentation/plugin-name-disambiguation' +import { useAppStore } from '@/store/index' import { PLUGIN_ACTION_TOAST_DURATION_MS } from './plugin-action-toast' import { usePluginIconThemeStore } from '@/store/plugins/appearance/plugin-icon-themes' import { usePluginThemeStore, usePluginTerminalThemeStore } from '@/store/plugins/appearance/plugin-themes' +import type { GlobalSettings } from '../../../../../shared/global-settings-types' +import type { PluginThemeRegistration } from '../../../../../shared/plugins/artifacts/plugin-theme-artifact' +import type { PluginTerminalThemeRegistration } from '../../../../../shared/plugins/artifacts/plugin-terminal-theme-artifact' export function isPluginAppThemeSelected( settings: Pick, diff --git a/src/renderer/src/components/plugins/view/plugin-view-request-handler.ts b/src/renderer/src/components/plugins/view/plugin-view-request-handler.ts index 335ead0288d..957a9bce9a6 100644 --- a/src/renderer/src/components/plugins/view/plugin-view-request-handler.ts +++ b/src/renderer/src/components/plugins/view/plugin-view-request-handler.ts @@ -9,8 +9,8 @@ import { import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host' import { detectLanguage } from '../../../../../shared/editor-language/editor-language-detect' import { activateAndRevealWorkspace } from '@/lib/workspace/activation/worktree-activation' -import { canShowRightSidebarForView } from '@/lib/right-sidebar-visibility' -import { useAppStore } from '@/store' +import { canShowRightSidebarForView } from '@/components/right-sidebar/visibility/right-sidebar-visibility' +import { useAppStore } from '@/store/index' import { selectFolderWorkspaces, selectWorktreesByRepo diff --git a/src/renderer/src/components/plugins/view/plugin-view-shown.ts b/src/renderer/src/components/plugins/view/plugin-view-shown.ts index 8182ed2aee9..000b7a7606f 100644 --- a/src/renderer/src/components/plugins/view/plugin-view-shown.ts +++ b/src/renderer/src/components/plugins/view/plugin-view-shown.ts @@ -1,4 +1,4 @@ -import { canShowRightSidebarForView } from '@/lib/right-sidebar-visibility' +import { canShowRightSidebarForView } from '@/components/right-sidebar/visibility/right-sidebar-visibility' import type { AppState } from '@/store/types' /** Why the panel is not on screen now, or null when it is the open right-sidebar tab. */ diff --git a/src/renderer/src/components/pull-request-page/checks/tab.tsx b/src/renderer/src/components/pull-request-page/checks/tab.tsx index b87c3675e4d..6d9f51e2b2e 100644 --- a/src/renderer/src/components/pull-request-page/checks/tab.tsx +++ b/src/renderer/src/components/pull-request-page/checks/tab.tsx @@ -2,14 +2,14 @@ import { isCompletePRCheckOwner } from '../../../../../shared/github/complete-pr import { usePRCheckRefreshOwner } from '@/hooks/use-pr-check-refresh-owner' import { getChecksTabSummaryPresentation } from '@/components/github-item-dialog/inspect-pull-request/checks-tab-summary' import React, { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { useMountedRef } from '@/hooks/useMountedRef' import { createGitHubChecksTabState, resolveGitHubChecksTabState, - toggleGitHubChecksTabExpandedKey, - type GitHubChecksContextOwner + toggleGitHubChecksTabExpandedKey } from '@/components/github-checks-tab-state' +import type { GitHubChecksContextOwner } from '@/components/github-checks-tab-state' import { getCheckDetailsKey } from '@/components/github/pr-check-presentation' import { getCheckCounts, @@ -26,15 +26,10 @@ import { canUseGitHubRepoContext, getGitHubSourceRuntimeHost } from '@/lib/work-items/github/github-source-runtime-context' -import { getLocalRepoProjectExecutionRuntimeContext } from '@/lib/local-preflight-context' +import { getLocalRepoProjectExecutionRuntimeContext } from '@/runtime/hosts/preflight/local-preflight-context' import { CLIENT_PLATFORM } from '@/lib/workspace/creation/new-workspace' import { resolveRepoExecutionHostPlatform } from '@/runtime/hosts/platform/execution-host-facts' import { resolveSourceControlActionRecipe } from '../../../../../shared/source-control/ai/source-control-ai-operation-policy' -import type { - GitHubWorkItem, - GitHubWorkItemDetails -} from '../../../../../shared/github/work-item-types' -import type { PRCheckDetail } from '../../../../../shared/github/check-types' import { refreshPullRequestChecks } from './refresh' import { rerunPullRequestChecks } from './rerun' import { requestPullRequestCheckDetails } from './details-request' @@ -44,6 +39,11 @@ import { CheckRow } from './row' import { ChecksFixDialog } from './fix-dialog' import { ChecksTabLayouts } from './layouts' import { useTranslate } from '@/i18n/use-translate' +import type { + GitHubWorkItem, + GitHubWorkItemDetails +} from '../../../../../shared/github/work-item-types' +import type { PRCheckDetail } from '../../../../../shared/github/check-types' export function ChecksTab({ item, diff --git a/src/renderer/src/components/pull-request-page/page/surface.tsx b/src/renderer/src/components/pull-request-page/page/surface.tsx index b86ed691ee1..15602e80dd4 100644 --- a/src/renderer/src/components/pull-request-page/page/surface.tsx +++ b/src/renderer/src/components/pull-request-page/page/surface.tsx @@ -8,11 +8,11 @@ import { GitPullRequestDraft } from 'lucide-react' import { toast } from 'sonner' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { useAllWorktrees } from '@/store/slices/worktrees/listing/use-worktree-catalog' import { findGithubPrWorkspaceAttachment } from '@/lib/work-items/github/github-work-item-workspace-attachment' import { activateAndRevealWorktree } from '@/lib/workspace/activation/worktree-activation' -import { getWorktreeAttachmentLabel } from '@/lib/worktree-attachment-label' +import { getWorktreeAttachmentLabel } from '@/lib/workspace/display/worktree-attachment-label' import { clearGitHubLinkCopied, createGitHubLinkCopyState, diff --git a/src/renderer/src/components/repo/RepoCombobox.tsx b/src/renderer/src/components/repo/RepoCombobox.tsx index b04d8fdb8f5..1fb831bef90 100644 --- a/src/renderer/src/components/repo/RepoCombobox.tsx +++ b/src/renderer/src/components/repo/RepoCombobox.tsx @@ -11,7 +11,7 @@ import { import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { useAppStore } from '@/store/index' import { isGitRepoKind } from '../../../../shared/repo-kind' -import { searchRepos } from '@/lib/repo-search' +import { searchRepos } from '@/lib/workspace/catalog/repo-search' import { cn } from '@/lib/class-names' import { useMountedRef } from '@/hooks/useMountedRef' import type { Repo } from '../../../../shared/repo-types' diff --git a/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.body-work.test.tsx b/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.body-work.test.tsx deleted file mode 100644 index f4534241e46..00000000000 --- a/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.body-work.test.tsx +++ /dev/null @@ -1,384 +0,0 @@ -import { getDefaultSettings } from '../../../../shared/constants' -// @vitest-environment happy-dom -import { act, type ReactNode } from 'react' -import { fireEvent, screen } from '@testing-library/react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { Worktree } from '../../../../shared/worktree/types' -import type * as WorktreeGitCopy from '@/lib/worktree-git-copy' -import type * as GitStatusClient from '@/runtime/source-control/git/runtime-git-status-client' -import type * as GitDiffClient from '@/runtime/source-control/git/runtime-git-diff-client' -import type * as RepoClient from '@/runtime/source-control/references/runtime-repo-client' -import { useAppStore } from '@/store' -import type { AppState } from '@/store/types' -import { TooltipProvider } from '@/components/ui/tooltip' -import FolderWorkspaceSourceControlPanel from './FolderWorkspaceSourceControlPanel' -import { ConfirmationDialogContext } from '@/components/confirmation-dialog-context' - -const probes = vi.hoisted(() => ({ visible: new Set() })) -const pending = (): Promise => new Promise(() => {}) - -vi.mock('./source-control/sync/git-status-refresh', () => ({ - refreshGitStatusForWorktree: async (args: { - worktreeId: string - request?: { onStatusAccepted?: (status: unknown) => void } - }) => { - args.request?.onStatusAccepted?.({ - entries: [], - conflictOperation: 'unknown', - branch: 'refs/heads/feature', - upstreamStatus: { hasUpstream: true, upstreamName: 'origin/feature', ahead: 0, behind: 0 } - }) - } -})) -vi.mock('./source-control/sync/use-refresh-on-host-contact', () => ({ - useRefreshOnHostContact: () => {} -})) -vi.mock('@/lib/worktree-git-copy', async (original) => ({ - ...(await original()), - resolveWorktreeGitCopyNow: (id: string, hostId: string) => ({ - worktreeId: id, - hostId, - transport: { kind: 'local' } - }) -})) -vi.mock('@/runtime/source-control/git/runtime-git-status-client', async (original) => ({ - ...(await original()), - setRuntimeGitStatusUpstreamRefWatch: async () => {}, - getRuntimeGitHistory: () => pending(), - getRuntimeGitSubmoduleStatus: () => pending() -})) -vi.mock('@/runtime/source-control/git/runtime-git-diff-client', async (original) => ({ - ...(await original()), - getRuntimeGitBranchCompare: async (_context: { worktreeId: string }, baseRef: string) => { - return { - summary: { - baseRef, - baseOid: 'base', - compareRef: 'feature', - headOid: 'head', - mergeBase: 'base', - changedFiles: 0, - status: 'ready' - }, - entries: [] - } - } -})) -vi.mock('@/runtime/source-control/references/runtime-repo-client', async (original) => ({ - ...(await original()), - watchRuntimeRepoBaseRefDefault: () => () => {}, - searchRuntimeRepoBaseRefs: async () => ['feature/live'] -})) - -// Report a section on screen only when the test made it visible, as a scrolled sidebar would. -const observed = new Map() -class ViewportIntersectionObserver implements IntersectionObserver { - readonly root = null - readonly rootMargin = '0px' - readonly scrollMargin = '0px' - readonly thresholds = [0] - constructor(private readonly callback: IntersectionObserverCallback) {} - report(target: Element): void { - const id = target.getAttribute('data-source-control-worktree') ?? '' - const bounds = target.getBoundingClientRect() - const entry: IntersectionObserverEntry = { - target, - isIntersecting: probes.visible.has(id), - boundingClientRect: bounds, - intersectionRect: bounds, - rootBounds: bounds, - intersectionRatio: probes.visible.has(id) ? 1 : 0, - time: performance.now() - } - this.callback([entry], this) - } - observe(target: Element): void { - observed.set(target, this) - this.report(target) - } - unobserve(target: Element): void { - observed.delete(target) - } - disconnect(): void { - for (const [target, observer] of observed) { - if (observer === this) { - observed.delete(target) - } - } - } - takeRecords(): IntersectionObserverEntry[] { - return [] - } -} -async function scrollTo(ids: readonly string[]): Promise { - probes.visible.clear() - for (const id of ids) { - probes.visible.add(id) - } - await act(async () => { - for (const [target, observer] of observed) { - if (observer instanceof ViewportIntersectionObserver) { - observer.report(target) - } - } - }) -} -let root: Root -let container: HTMLDivElement -const refuseConfirmation = async () => false - -beforeEach(() => { - vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true) - vi.stubGlobal('IntersectionObserver', ViewportIntersectionObserver) - const namespace = new Proxy( - {}, - { - get: (_target, method) => - typeof method === 'string' && method.startsWith('on') ? () => () => {} : pending - } - ) - vi.stubGlobal('api', new Proxy({}, { get: () => namespace })) - vi.useFakeTimers() - useAppStore.setState(useAppStore.getInitialState(), true) - container = document.createElement('div') - document.body.append(container) - root = createRoot(container) - probes.visible.clear() - observed.clear() -}) -afterEach(async () => { - await act(async () => root.unmount()) - container.remove() - vi.useRealTimers() - vi.unstubAllGlobals() -}) - -function setup(count: number): Worktree[] { - const worktrees: Worktree[] = Array.from({ length: count }, (_, i) => ({ - id: `repo::/child-${i}`, - repoId: 'repo', - path: `/child-${i}`, - branch: `refs/heads/feature-${i}`, - head: 'abc123', - isBare: false, - isMainWorktree: false, - displayName: `Child ${i}`, - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: i, - lastActivityAt: 0, - hostId: 'local' as const, - instanceId: `instance-${i}` - })) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: fixture supplies the catalog, status and probed actions the panels read. - useAppStore.setState({ - settings: getDefaultSettings('/tmp'), - activeWorktreeId: 'folder:feature', - activeWorkspaceKey: 'folder:feature', - activeWorkspaceExecutionHostId: 'local', - rightSidebarOpen: true, - rightSidebarTab: 'source-control', - repos: [ - { - id: 'repo', - displayName: 'Child', - path: '/repo', - kind: 'git', - worktreeBaseRef: 'origin/main' - } - ], - worktreesByRepo: { repo: worktrees }, - folderWorkspaces: [ - { id: 'feature', name: 'Feature', folderPath: '/folder', projectGroupId: 'group' } - ], - workspaceLineageByChildKey: Object.fromEntries( - worktrees.map((row, i) => [ - row.id, - { - childWorkspaceKey: `worktree:${row.id}`, - childInstanceId: row.instanceId, - parentWorkspaceKey: 'folder:feature', - parentInstanceId: null, - createdAt: i - } - ]) - ), - // Changed sections start expanded, so every body would mount without the viewport gate. - gitStatusByWorktree: Object.fromEntries( - worktrees.map((row) => [row.id, [{ path: 'a.ts', status: 'modified', area: 'unstaged' }]]) - ), - fetchUpstreamStatus: async () => {}, - getHostedReviewCreationEligibility: pending, - fetchHostedReviewForBranch: async () => null, - fetchPRForBranch: async () => null - } as unknown as Partial) - return worktrees -} - -async function render(node: ReactNode): Promise { - await act(async () => - root.render( - - {node} - - ) - ) - await act(async () => { - await vi.advanceTimersByTimeAsync(0) - }) -} - -it.each(['off-screen', 'collapsed'])( - 'keeps selection and draft while %s and resumes the current owner snapshot', - async (inactive) => { - const worktrees = setup(3) - const [first] = worktrees - await scrollTo([first!.id]) - await render() - const section = container.querySelector(`[data-source-control-worktree="${first!.id}"]`) - const row = section?.querySelector('[data-testid="source-control-entry"]') - expect(row).toBeTruthy() - // Both modifiers select on either platform without triggering split open. - await act(async () => - row!.dispatchEvent(new MouseEvent('click', { bubbles: true, ctrlKey: true, metaKey: true })) - ) - expect(section?.textContent).toContain('1 selected') - - const draft = section!.querySelector('textarea')! - const setValue = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set! - await act(async () => { - setValue.call(draft, 'fix: keep my draft') - draft.dispatchEvent(new Event('input', { bubbles: true })) - draft.dispatchEvent(new Event('change', { bubbles: true })) - }) - expect(draft.value).toBe('fix: keep my draft') - await (inactive === 'off-screen' - ? scrollTo([]) - : act(async () => - section!.querySelector('button[aria-expanded]')!.click() - )) - await act(async () => - useAppStore.setState((state) => ({ - worktreesByRepo: { - repo: state.worktreesByRepo.repo!.map((row) => - row.id === first!.id ? { ...row, branch: 'refs/heads/current-branch' } : row - ) - }, - gitStatusByWorktree: { - ...state.gitStatusByWorktree, - [first!.id]: [ - ...state.gitStatusByWorktree[first!.id]!, - { path: 'latest.ts', status: 'modified', area: 'unstaged' } - ] - } - })) - ) - expect(section!.querySelector('[data-source-control-path="latest.ts"]')).toBeNull() - await act(async () => { - await vi.advanceTimersByTimeAsync(60_000) - }) - - await (inactive === 'off-screen' - ? scrollTo([first!.id]) - : act(async () => - section!.querySelector('button[aria-expanded]')!.click() - )) - expect(section?.textContent).toContain('1 selected') - expect(section!.querySelector('[data-source-control-path="latest.ts"]')).toBeTruthy() - expect(section!.querySelector('textarea')!.value).toBe( - 'fix: keep my draft' - ) - } -) - -it('opens a deleted section entry as its diff from Open in File Explorer', async () => { - const [owner] = setup(1) - useAppStore.setState({ - gitStatusByWorktree: { - [owner!.id]: [{ path: 'deleted.ts', status: 'deleted', area: 'unstaged' }] - } - }) - probes.visible.add(owner!.id) - const openDiff = vi.spyOn(useAppStore.getState(), 'openDiff').mockImplementation(() => {}) - const openFile = vi.spyOn(useAppStore.getState(), 'openFile').mockImplementation(() => 'unused') - await render() - const row = container.querySelector('[data-testid="source-control-entry"]')! - await act(async () => - row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, button: 2 })) - ) - const item = [...document.querySelectorAll('[role="menuitem"]')].find((node) => - node.textContent?.includes('Open in File Explorer') - ) - expect(item).toBeTruthy() - await act(async () => item!.click()) - expect(openDiff).toHaveBeenCalledWith( - owner!.id, - '/child-0/deleted.ts', - 'deleted.ts', - 'typescript', - false, - expect.objectContaining({ placementWorkspaceId: 'folder:feature' }) - ) - expect(openFile).not.toHaveBeenCalled() -}) - -it('split-opens child content in the current placement group after a focus change', async () => { - const [owner] = setup(1) - probes.visible.add(owner!.id) - const createSplit = vi.fn(() => 'new-split') - const openDiff = vi.fn() - useAppStore.setState({ createEmptySplitGroup: createSplit, openDiff }) - await render() - await act(async () => - useAppStore.setState({ - activeGroupIdByWorktree: { 'folder:feature': 'current-group' }, - groupsByWorktree: { - 'folder:feature': [ - { id: 'current-group', worktreeId: 'folder:feature', tabOrder: [], activeTabId: null } - ] - } - }) - ) - const row = container.querySelector('[data-testid="source-control-entry"]')! - await act(async () => row.dispatchEvent(new MouseEvent('click', { bubbles: true, altKey: true }))) - expect(createSplit).toHaveBeenCalledWith('folder:feature', 'current-group', 'right') - expect(openDiff).toHaveBeenCalledWith( - owner!.id, - '/child-0/a.ts', - 'a.ts', - 'typescript', - false, - expect.objectContaining({ - placementWorkspaceId: 'folder:feature', - targetGroupId: 'new-split', - preview: false - }) - ) -}) - -it('keeps an owned base-ref dialog usable after its section leaves the viewport and collapses', async () => { - const worktrees = setup(3) - probes.visible.add(worktrees[0]!.id) - await render() - const changeBase = screen.getByRole('button', { name: /Change base ref/ }) - await act(async () => fireEvent.click(changeBase)) - await scrollTo([]) - const section = container.querySelector('section')! - const collapse = section.querySelector('button[aria-expanded="true"]')! - await act(async () => fireEvent.click(collapse)) - await act(async () => { - fireEvent.change(screen.getByPlaceholderText('Search branches by name...'), { - target: { value: 'feature' } - }) - }) - await act(async () => { - await vi.advanceTimersByTimeAsync(250) - }) - expect(screen.getByRole('button', { name: 'feature/live' })).toBeTruthy() -}) diff --git a/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.test.tsx b/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.test.tsx deleted file mode 100644 index 34290b57abf..00000000000 --- a/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.test.tsx +++ /dev/null @@ -1,278 +0,0 @@ -// @vitest-environment happy-dom -import { act } from 'react' -import type { Worktree } from '../../../../shared/worktree/types' -import type * as GitIdentityDisplay from '../../../../shared/worktree/git-identity-display' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' -import type { AppState } from '@/store/types' -import { TooltipProvider } from '@/components/ui/tooltip' -import FolderWorkspaceSourceControlPanel from './FolderWorkspaceSourceControlPanel' -import { useSourceControlWatchConsumers } from '@/hooks/source-control-watch-consumers' -import { - useSourceControlScope, - type SourceControlScope -} from './source-control/panel/worktree-scope' -import { useWorktreeGitStatusObservation } from './source-control/sync/use-worktree-git-status-observation' -import { ORCA_WORKTREE_FILE_CHANGE_EVENT } from '@/hooks/worktree-file-change-event' - -const probes = vi.hoisted(() => ({ - status: vi.fn(async (_request: { worktreeId: string }) => {}), - body: vi.fn(), - header: vi.fn(), - watches: new Array() -})) -vi.mock('./source-control/sync/git-status-refresh', () => ({ - refreshGitStatusForWorktree: probes.status -})) -vi.mock('./source-control/sync/use-git-status-upstream-ref-watch', () => ({ - useGitStatusUpstreamRefWatch: () => undefined -})) -vi.mock('./source-control/sync/use-refresh-on-host-contact', () => ({ - useRefreshOnHostContact: () => {} -})) -vi.mock('@/lib/worktree-git-copy', () => ({ - resolveWorktreeGitCopyNow: (id: string, hostId: string) => ({ - worktreeId: id, - hostId, - transport: { kind: 'local' } - }) -})) -vi.mock('../../../../shared/worktree/git-identity-display', async (original) => { - const actual = await original() - return { - ...actual, - getWorktreeGitIdentityDisplay: ( - ...args: Parameters - ) => { - probes.header(args[0].branch) - return actual.getWorktreeGitIdentityDisplay(...args) - } - } -}) -vi.mock('./source-control/panel/panel', () => ({ - SourceControlPanel: () => { - const scope = useSourceControlScope() - probes.body(scope?.worktreeId) - return
- } -})) - -// Unlike happy-dom, report every observed section as on screen. -class OnScreenIntersectionObserver { - private readonly callback: IntersectionObserverCallback - constructor(callback: IntersectionObserverCallback) { - this.callback = callback - } - observe(target: Element): void { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the section hook reads only target and isIntersecting. - this.callback([{ target, isIntersecting: true } as IntersectionObserverEntry], this as never) - } - unobserve(): void {} - disconnect(): void {} -} - -let root: Root -let container: HTMLDivElement -beforeEach(() => { - vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true) - vi.stubGlobal('IntersectionObserver', OnScreenIntersectionObserver) - vi.useFakeTimers() - useAppStore.setState(useAppStore.getInitialState(), true) - container = document.createElement('div') - document.body.append(container) - root = createRoot(container) - probes.status.mockClear() - probes.body.mockClear() - probes.header.mockClear() -}) -afterEach(async () => { - await act(async () => root.unmount()) - container.remove() - vi.useRealTimers() - vi.restoreAllMocks() - vi.unstubAllGlobals() -}) -function Watches() { - probes.watches = useSourceControlWatchConsumers().map((target) => target.worktreeId) - return null -} -function setup(count: number) { - const worktrees: Worktree[] = Array.from({ length: count }, (_, i) => ({ - id: `repo::/child-${i}`, - repoId: 'repo', - path: `/child-${i}`, - branch: `feature-${i}`, - head: 'abc123', - isBare: false, - isMainWorktree: false, - displayName: `Child ${i}`, - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: i, - lastActivityAt: 0, - hostId: 'local' as const, - instanceId: `instance-${i}` - })) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: fixture supplies the catalog and status fields consumed by the folder panel. - useAppStore.setState({ - activeWorktreeId: 'folder:feature', - activeWorkspaceKey: 'folder:feature', - activeWorkspaceExecutionHostId: 'local', - rightSidebarOpen: true, - rightSidebarTab: 'source-control', - repos: [{ id: 'repo', displayName: 'Child', path: '/repo', kind: 'git' }], - worktreesByRepo: { repo: worktrees }, - folderWorkspaces: [ - { id: 'feature', name: 'Feature', folderPath: '/folder', projectGroupId: 'group' } - ], - workspaceLineageByChildKey: Object.fromEntries( - worktrees.map((row, i) => [ - row.id, - { - childWorkspaceKey: `worktree:${row.id}`, - childInstanceId: row.instanceId, - parentWorkspaceKey: 'folder:feature', - parentInstanceId: null, - createdAt: i - } - ]) - ), - gitStatusByWorktree: Object.fromEntries(worktrees.map((row) => [row.id, []])) - } as unknown as Partial) - return worktrees -} -async function render(visible = true) { - await act(async () => - root.render( - - - {visible && } - - ) - ) -} - -it('labels same-repo sections by worktree name and a detached section by its HEAD', async () => { - const [onBranch, detached] = setup(2) - useAppStore.setState({ - worktreesByRepo: { repo: [onBranch!, { ...detached!, branch: '', head: 'abc1234def' }] } - }) - await render() - expect( - [...container.querySelectorAll('section button[aria-expanded]')].map( - (toggle) => toggle.textContent - ) - ).toEqual(['ChildChild 0feature-0', 'ChildChild 1Detached HEAD · abc1234']) -}) - -function ScopedStatusObserver({ owner }: { owner: SourceControlScope }) { - useWorktreeGitStatusObservation(owner, { enabled: true }) - return null -} - -it('filters file events by the section runtime host when a same-id local twin exists', async () => { - const [local] = setup(1) - const remote = { ...local!, hostId: 'runtime:paired' as const, instanceId: 'remote-instance' } - const repo = useAppStore.getState().repos[0]! - const owner: SourceControlScope = { - worktreeId: remote.id, - repoId: remote.repoId, - executionHostId: 'runtime:paired', - worktree: remote, - repo, - attachedAt: 0, - placementWorkspaceId: 'folder:feature' - } - useAppStore.setState({ worktreesByRepo: { repo: [local!, remote] } }) - await act(async () => root.render()) - expect(probes.status).toHaveBeenCalledTimes(1) - probes.status.mockClear() - for (const runtimeEnvironmentId of [null, 'other-runtime', 'paired']) { - await act(async () => { - window.dispatchEvent( - new CustomEvent(ORCA_WORKTREE_FILE_CHANGE_EVENT, { - detail: { - runtimeEnvironmentId, - payload: { - worktreePath: remote.path, - events: [{ absolutePath: `${remote.path}/a.ts`, kind: 'change' }] - } - } - }) - ) - await vi.advanceTimersByTimeAsync(4000) - }) - expect(probes.status).toHaveBeenCalledTimes(runtimeEnvironmentId === 'paired' ? 1 : 0) - } -}) - -it('includes a paired-runtime descendant of a local attached worktree as a section', async () => { - const [parent] = setup(1) - const remote = { - ...parent!, - id: 'remote-repo::/remote-child', - repoId: 'remote-repo', - path: '/remote-child', - displayName: 'Remote child', - hostId: 'runtime:paired' as const, - runtimeOwnerEnvironmentId: 'paired', - instanceId: 'remote-instance' - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the shared lineage selector reads only the status descriptor's installation identity. - useAppStore.setState({ - repos: [ - ...useAppStore.getState().repos, - { - id: 'remote-repo', - displayName: 'Remote', - path: '/remote', - kind: 'git', - executionHostId: 'runtime:paired' - } - ], - worktreesByRepo: { repo: [parent!], 'remote-repo': [remote] }, - ownLineageInstallationId: 'local-install', - runtimeStatusByEnvironmentId: new Map([ - [ - 'paired', - { - status: { hostDescriptor: { installationId: 'remote-install' } }, - checkedAt: 1 - } - ] - ]), - crossStoreLineageByStoreKey: { - paired: { - [`worktree:${remote.id}`]: { - childWorkspaceKey: `worktree:${remote.id}`, - childInstanceId: 'remote-instance', - parent: { - installationId: 'local-install', - workspaceKey: `worktree:${parent!.id}`, - instanceId: 'instance-0' - }, - origin: 'manual', - capture: { source: 'explicit-ui', confidence: 'explicit' }, - createdAt: 2 - } - } - }, - gitStatusByWorktree: { [parent!.id]: [], [remote.id]: [] } - } as unknown as Partial) - await render() - expect( - [...container.querySelectorAll('section')].map((section) => - section.getAttribute('data-source-control-worktree') - ) - ).toEqual([parent!.id, 'remote-repo::/remote-child']) - expect(probes.status.mock.calls.map(([request]) => request.worktreeId)).toEqual([ - parent!.id, - 'remote-repo::/remote-child' - ]) -}) diff --git a/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.tsx b/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.tsx index b8424d28834..4886a2d68ab 100644 --- a/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.tsx +++ b/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.tsx @@ -4,7 +4,7 @@ import { } from '@/store/slices/worktrees/metadata/cross-store-lineage-parents' import { memo, useCallback, useEffect, useMemo, useState } from 'react' import { RefreshCw } from 'lucide-react' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { selectFolderWorkspaces, selectWorktreesByRepo @@ -13,7 +13,7 @@ import { getAttachedWorktreesForFolderWorkspace, attachedWorktreeOwnerKey } from './folder-workspace-attached-worktrees' -import { resolveReviewRepository } from '@/lib/review-owner' +import { resolveReviewRepository } from '@/lib/source-control/review/review-owner' import { useTranslate } from '@/i18n/use-translate' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' import { OverlayActivityOwner } from '@/components/ui/use-overlay-focus-scope' @@ -26,6 +26,8 @@ import { SourceControlScopeProvider, type SourceControlScope } from './source-control/panel/worktree-scope' +import { SourceControlHeaderOverflowMenu } from './source-control/panel/header-overflow-menu' +import { SourceControlHeaderActionsSlot } from './source-control/panel/header-actions-slot' import { useWorktreeGitStatusObservation } from './source-control/sync/use-worktree-git-status-observation' import { useSourceControlWatchConsumer } from '@/hooks/source-control-watch-consumers' import { useSectionOnScreen } from './source-control/panel/section-viewport-presence' @@ -112,6 +114,7 @@ const WorktreeSection = memo( : null ) const panel = useMemo(() => , []) + const [actionsSlot, setActionsSlot] = useState(null) const identity = getWorktreeGitIdentityDisplay(owner.worktree) return (
+ ) : null + } onToggle={() => setExpanded(!isExpanded)} onOpen={() => useAppStore.getState().setActiveWorktree(id, owner.executionHostId)} + actionsSlotRef={setActionsSlot} /> {isExpanded && (!connected ? ( @@ -154,9 +164,11 @@ const WorktreeSection = memo( // A read error renders the body's existing failure banner with Retry. )} diff --git a/src/renderer/src/components/right-sidebar/FolderWorkspaceWorktreesPanel.tsx b/src/renderer/src/components/right-sidebar/FolderWorkspaceWorktreesPanel.tsx index b1c692f6d1c..f5ceec4583b 100644 --- a/src/renderer/src/components/right-sidebar/FolderWorkspaceWorktreesPanel.tsx +++ b/src/renderer/src/components/right-sidebar/FolderWorkspaceWorktreesPanel.tsx @@ -8,11 +8,10 @@ import { getLineageChildrenInlineStyle, LINEAGE_CHILDREN_INLINE_OFFSET } from '@/components/sidebar/worktree-list/rows/indentation' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { useTranslate } from '@/i18n/use-translate' import { getWorktreeHostIdentity } from '../../../../shared/worktree/host-qualified-identity' -import { resolveReviewRepository } from '@/lib/review-owner' -import type { Worktree } from '../../../../shared/worktree/types' +import { resolveReviewRepository } from '@/lib/source-control/review/review-owner' import { getAttachedWorktreesForFolderWorkspace } from './folder-workspace-attached-worktrees' import { useState } from 'react' import { @@ -20,6 +19,7 @@ import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' import { FolderWorkspaceEmptyState } from './folder-workspace-empty-state' +import type { Worktree } from '../../../../shared/worktree/types' export default function FolderWorkspaceWorktreesPanel(): React.JSX.Element { const t = useTranslate() diff --git a/src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-saved-session-lists.ts b/src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-saved-session-lists.ts index b40e7397b39..a21b69d3b7a 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-saved-session-lists.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-saved-session-lists.ts @@ -1,9 +1,5 @@ // Last list per scope, kept across restarts so History can paint it while the rescan runs. -import type { - AiVaultListResult, - AiVaultSession -} from '../../../../../../shared/ai-vault/contracts/ai-vault-types' import { latestSessionConversationTurn } from '../../../../../../shared/ai-vault/session-display/ai-vault-session-display' import { useAppStore } from '@/store/index' import { isWebClientLocation } from '@/app-shell/platform/web-client-location' @@ -11,8 +7,12 @@ import { committedTransaction, indexedDbConnection, settledRequest -} from '@/lib/indexeddb-connection' +} from '@/app-shell/storage/indexeddb-connection' import { catalogRowsEqual } from '@/lib/catalog-reconciliation/catalog-row-reconciliation' +import type { + AiVaultListResult, + AiVaultSession +} from '../../../../../../shared/ai-vault/contracts/ai-vault-types' import type { AiVaultSessionLimit } from '../session-list/ai-vault-session-limit' const DATABASE_NAME = 'orca-ai-vault-session-lists' diff --git a/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-original-pane-actions.ts b/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-original-pane-actions.ts index b27eba0bc1a..d03fb7f2749 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-original-pane-actions.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-original-pane-actions.ts @@ -5,11 +5,9 @@ import { activateTabAndFocusPane } from '@/lib/workspace/tabs/activate-tab-and-f import { activateAndRevealWorkspace } from '@/lib/workspace/activation/worktree-activation' import { findFolderWorkspaceOwner } from '@/lib/workspace/ownership/folder-workspace-runtime-owner' import { useAppStore } from '@/store/index' -import { openDesktopStructuredSession } from '@/lib/activate-ai-vault-structured-session' +import { openDesktopStructuredSession } from '@/lib/agent-session/open/activate-ai-vault-structured-session' import { findStructuredAgentSessionTab } from '@/lib/agent-session/structured-agent-session-tab-activation' import { flashFocusedPaneRim } from '@/components/terminal-pane/input/focus/focused-pane-rim-flash' -import type { AgentDotState } from '@/components/AgentStateDot' -import type { AiVaultSession } from '../../../../../../shared/ai-vault/contracts/ai-vault-types' import { translate } from '@/i18n/i18n' import { parseWorkspaceKey } from '../../../../../../shared/workspace-scope' import { findOriginalAiVaultSessionPane } from './ai-vault-original-pane' @@ -18,6 +16,8 @@ import { findAiVaultSessionLiveStateInIndex, findOriginalAiVaultSessionPaneInIndex } from './ai-vault-original-pane-index' +import type { AgentDotState } from '@/components/AgentStateDot' +import type { AiVaultSession } from '../../../../../../shared/ai-vault/contracts/ai-vault-types' export function useAiVaultOriginalPaneActions(): { getOriginalPaneTarget: ( diff --git a/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-session-launch-actions.ts b/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-session-launch-actions.ts index b7312cb9b42..981b729582a 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-session-launch-actions.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-session-launch-actions.ts @@ -8,39 +8,39 @@ import { buildAiVaultResumeCopyCommandForWorktree, buildAiVaultResumeStartupForWorktree } from '@/lib/agent-session/resume/history/ai-vault-resume-command' -import type { - AiVaultResumeCommandSession, - AiVaultResumeStartup -} from '../../../../../../shared/ai-vault/resume/ai-vault-resume-startup' import { assertAiVaultCopiedSessionLaunchAllowed, buildAiVaultCopiedSessionStartupForWorktree, buildAiVaultForkStartupForWorktree } from '@/lib/agent-session/resume/history/ai-vault-session-fork-startup' -import { launchAiVaultSessionAndReveal } from '@/lib/launch-ai-vault-session-and-reveal' +import { launchAiVaultSessionAndReveal } from '@/lib/agent-session/resume/history/launch-ai-vault-session-and-reveal' import { useAppStore } from '@/store/index' -import type { - AiVaultAgent, - AiVaultSession -} from '../../../../../../shared/ai-vault/contracts/ai-vault-types' import { dropDeletedRemoteResumeCwd, prepareAiVaultSessionForFork, prepareAiVaultSessionForResume, prepareAiVaultSessionForTerminalResume } from '@/lib/agent-session/resume/history/ai-vault-session-resume-preparation' -import type { Worktree } from '../../../../../../shared/worktree/types' import { translate } from '@/i18n/i18n' import { describeAiVaultCliForkFailure } from './ai-vault-session-cli-fork' -import type { AiVaultSessionResumeTargetState } from './ai-vault-session-resume' import { prepareAiVaultSessionContinuation } from './ai-vault-session-continuation' -import type { AgentSessionContinuationRequest } from '@/lib/agent-session/context/agent-session-continuation' -import { activateAiVaultStructuredSession } from '@/lib/activate-ai-vault-structured-session' +import { activateAiVaultStructuredSession } from '@/lib/agent-session/open/activate-ai-vault-structured-session' import { adoptsCliConversations } from '../../../../../../shared/structured-agent-cli-conversation-adoption' import { newAgentLaunchRequestId } from '@/lib/agent-session/launch/routing/agent-launch-request-id' import { describeAiVaultResumeFailure } from '@/lib/agent-session/resume/history/ai-vault-resume-refusal' import { resumeAiVaultSessionInNewChat } from './ai-vault-session-resume-in-chat-launch' import { resolveAiVaultTargetWorkspacePath } from './ai-vault-session-launch-target' +import type { + AiVaultResumeCommandSession, + AiVaultResumeStartup +} from '../../../../../../shared/ai-vault/resume/ai-vault-resume-startup' +import type { + AiVaultAgent, + AiVaultSession +} from '../../../../../../shared/ai-vault/contracts/ai-vault-types' +import type { Worktree } from '../../../../../../shared/worktree/types' +import type { AiVaultSessionResumeTargetState } from './ai-vault-session-resume' +import type { AgentSessionContinuationRequest } from '@/lib/agent-session/context/agent-session-continuation' export function useAiVaultSessionLaunchActions({ activeWorktree, diff --git a/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-session-resume-here.ts b/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-session-resume-here.ts index bea7b4a11ae..b5ccefbe2f3 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-session-resume-here.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-session-resume-here.ts @@ -3,29 +3,27 @@ import { useAppStore } from '@/store/index' import { activateAiVaultStructuredSession, openDesktopStructuredSession -} from '@/lib/activate-ai-vault-structured-session' -import { insertUnifiedTabAfterAnchor } from '@/lib/unified-tab-anchor-insertion' +} from '@/lib/agent-session/open/activate-ai-vault-structured-session' +import { insertUnifiedTabAfterAnchor } from '@/lib/workspace/tabs/unified-tab-anchor-insertion' import { newAgentLaunchRequestId } from '@/lib/agent-session/launch/routing/agent-launch-request-id' import { captureNativeChatComposerFocusIntent, requestNativeChatComposerFocus } from '@/components/native-chat/composer/focus/native-chat-composer-focus-intent' -import type { ConfirmationDialogContextValue } from '@/components/confirmation-dialog-context' import { translate } from '@/i18n/i18n' import { agentLabel } from '../../../../../../shared/ai-vault/session-display/ai-vault-session-filters' -import { - aiVaultHistoryAgents, - type AiVaultAgent, - type AiVaultSession +import { aiVaultHistoryAgents } from '../../../../../../shared/ai-vault/contracts/ai-vault-types' +import type { + AiVaultAgent, + AiVaultSession } from '../../../../../../shared/ai-vault/contracts/ai-vault-types' -import { - adoptsCliConversations, - type CliConversationRowAgent -} from '../../../../../../shared/structured-agent-cli-conversation-adoption' -import type { Tab } from '../../../../../../shared/tab-types' +import { adoptsCliConversations } from '../../../../../../shared/structured-agent-cli-conversation-adoption' +import type { CliConversationRowAgent } from '../../../../../../shared/structured-agent-cli-conversation-adoption' import { structuredLaunchConversationOwner } from '@/lib/agent-session/launch/structured-agent-session-launch-failure' -import type { AiVaultSessionRowChatActions } from './ai-vault-session-chat-action' import { resumeAiVaultSessionInNewChat } from './ai-vault-session-resume-in-chat-launch' +import type { ConfirmationDialogContextValue } from '@/components/confirmation-dialog-context' +import type { Tab } from '../../../../../../shared/tab-types' +import type { AiVaultSessionRowChatActions } from './ai-vault-session-chat-action' /** The chat `/resume` was typed in; a picked row's conversation takes its place. */ export type AiVaultResumeHere = { diff --git a/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-session-resume-in-chat-launch.ts b/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-session-resume-in-chat-launch.ts index 7da5d121413..6f5ebe0a743 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-session-resume-in-chat-launch.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-session-resume-in-chat-launch.ts @@ -1,20 +1,14 @@ import { toast } from 'sonner' -import { - parseRoutableExecutionHostId, - type ExecutionHostId -} from '../../../../../../shared/execution-host' +import { parseRoutableExecutionHostId } from '../../../../../../shared/execution-host' +import type { ExecutionHostId } from '../../../../../../shared/execution-host' import { translate } from '@/i18n/i18n' import { useAppStore } from '@/store/index' -import type { AiVaultSession } from '../../../../../../shared/ai-vault/contracts/ai-vault-types' import { agentLabel } from '../../../../../../shared/ai-vault/session-display/ai-vault-session-filters' -import { - CLI_CONVERSATION_ADOPTING_AGENTS, - type CliConversationRowAgent -} from '../../../../../../shared/structured-agent-cli-conversation-adoption' +import { CLI_CONVERSATION_ADOPTING_AGENTS } from '../../../../../../shared/structured-agent-cli-conversation-adoption' +import type { CliConversationRowAgent } from '../../../../../../shared/structured-agent-cli-conversation-adoption' import { hasRuntimeRpcErrorCode } from '../../../../../../shared/runtime-rpc-error-code' import { prepareAiVaultSessionForResume } from '@/lib/agent-session/resume/history/ai-vault-session-resume-preparation' import { adoptAgentSessionLaunchVerdict } from '@/lib/agent-session/launch/routing/agent-session-launch-plan' -import type { AgentLaunchRequestId } from '@/lib/agent-session/launch/routing/agent-launch-request-id' import { activateAndRevealWorkspace } from '@/lib/workspace/activation/worktree-activation' import { beginStructuredAgentSessionProvisionalLaunch, @@ -22,10 +16,12 @@ import { } from '@/lib/agent-session/structured-agent-session-provisional-tab' import { admitStructuredLaunchOnHost } from '@/lib/agent-session/launch/structured-agent-session-host-admission' import { toRuntimeWorktreeSelector } from '@/runtime/rpc/targets/runtime-worktree-selector' -import { cliConversationExitGuidance } from '@/lib/cli-conversation-exit-guidance' +import { cliConversationExitGuidance } from '@/lib/agent-session/resume/history/cli-conversation-exit-guidance' import { structuredLaunchFailure } from '@/lib/agent-session/launch/structured-agent-session-launch-failure' import { workspaceHasSleepingAgentSessions } from '@/lib/workspace/activation/worktree-agent-activation-gate' import { resolveWebSessionVisibleTabId } from '@/runtime/web-session-tabs-sync/navigation/web-session-focus-intent' +import type { AiVaultSession } from '../../../../../../shared/ai-vault/contracts/ai-vault-types' +import type { AgentLaunchRequestId } from '@/lib/agent-session/launch/routing/agent-launch-request-id' import type { TuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent' import type { StructuredAgentLaunchSettlement } from '@/lib/agent-session/launch/continuation/structured-agent-launch-settlement' import type { NativeChatComposerFocusIntent } from '@/components/native-chat/composer/focus/native-chat-composer-focus-intent' diff --git a/src/renderer/src/components/right-sidebar/ai-vault/session-list/use-ai-vault-session-display-title.ts b/src/renderer/src/components/right-sidebar/ai-vault/session-list/use-ai-vault-session-display-title.ts index 65754fe969d..56d812271dc 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault/session-list/use-ai-vault-session-display-title.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault/session-list/use-ai-vault-session-display-title.ts @@ -1,8 +1,8 @@ -import type { AiVaultSession } from '../../../../../../shared/ai-vault/contracts/ai-vault-types' import { structuredChatDisplayName } from '../../../../../../shared/structured-chat-row-name' import { useAppStore } from '@/store/index' -import { structuredChatTabBySessionId } from '@/lib/structured-chat-tab-index' +import { structuredChatTabBySessionId } from '@/lib/agent-session/tab-identity/structured-chat-tab-index' import { useStructuredConversationName } from '@/runtime/native-chat/naming/structured-conversation-name' +import type { AiVaultSession } from '../../../../../../shared/ai-vault/contracts/ai-vault-types' /** Native rows use live saved names, falling back to authoritative host titles across closed tabs and restarts. */ export function useAiVaultSessionDisplayTitle(session: AiVaultSession): string { diff --git a/src/renderer/src/components/right-sidebar/checks-panel/refresh/use-checks-panel-git-status-effects.tsx b/src/renderer/src/components/right-sidebar/checks-panel/refresh/use-checks-panel-git-status-effects.tsx index 2caea4d0210..9dc96a0fbeb 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/refresh/use-checks-panel-git-status-effects.tsx +++ b/src/renderer/src/components/right-sidebar/checks-panel/refresh/use-checks-panel-git-status-effects.tsx @@ -2,7 +2,7 @@ import { getRepoExecutionHostId } from '../../../../../../shared/execution-host' import { useEffect, useRef } from 'react' import { getRuntimeGitStatus } from '@/runtime/source-control/git/runtime-git-status-client' import { getRuntimeGitUpstreamStatus } from '@/runtime/source-control/git/runtime-git-sync-client' -import { resolveWorktreeGitCopyNow } from '@/lib/worktree-git-copy' +import { resolveWorktreeGitCopyNow } from '@/lib/workspace/ownership/worktree-git-copy' import { buildChecksPanelEligibilityGitFingerprint, shouldClearChecksPanelGitStatusSnapshot, diff --git a/src/renderer/src/components/right-sidebar/checks-panel/refresh/use-checks-panel-manual-refresh.tsx b/src/renderer/src/components/right-sidebar/checks-panel/refresh/use-checks-panel-manual-refresh.tsx index cf8091e793a..34e3a3cef18 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/refresh/use-checks-panel-manual-refresh.tsx +++ b/src/renderer/src/components/right-sidebar/checks-panel/refresh/use-checks-panel-manual-refresh.tsx @@ -4,7 +4,7 @@ import { useAppStore } from '@/store/index' import { buildGitHubPRRefreshStateClearToken } from '@/store/github/refresh/pr-refresh-state' import { getRuntimeGitStatus } from '@/runtime/source-control/git/runtime-git-status-client' import { getRuntimeGitUpstreamStatus } from '@/runtime/source-control/git/runtime-git-sync-client' -import { resolveWorktreeGitCopyNow } from '@/lib/worktree-git-copy' +import { resolveWorktreeGitCopyNow } from '@/lib/workspace/ownership/worktree-git-copy' import { hasChecksPanelGitStatusBranchChanged, readChecksPanelRefreshGitIdentitySnapshot, diff --git a/src/renderer/src/components/right-sidebar/checks-panel/review-actions/use-checks-panel-generation.tsx b/src/renderer/src/components/right-sidebar/checks-panel/review-actions/use-checks-panel-generation.tsx index c8ddf92cf2f..1798c1cf88f 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/review-actions/use-checks-panel-generation.tsx +++ b/src/renderer/src/components/right-sidebar/checks-panel/review-actions/use-checks-panel-generation.tsx @@ -5,7 +5,7 @@ import type { PullRequestGenerationOutcome } from '../../hosted-review/creation/ import { settlePullRequestGenerationRequest } from '../../hosted-review/creation/pull-request-generation-request-outcome' import { useAppStore } from '@/store/index' import { getConnectionId } from '@/lib/workspace/ownership/connection-context' -import { resolveWorktreeGitCopyNow } from '@/lib/worktree-git-copy' +import { resolveWorktreeGitCopyNow } from '@/lib/workspace/ownership/worktree-git-copy' import { generateRuntimePullRequestFields, cancelRuntimeGeneratePullRequestFields diff --git a/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-controller-state.tsx b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-controller-state.tsx index 61fa4ba4d1b..eb2ced512ce 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-controller-state.tsx +++ b/src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-controller-state.tsx @@ -1,7 +1,7 @@ import { useCallback, useMemo, useRef, useState, type SetStateAction } from 'react' import { useWorktreeGitOwnerTarget } from '../source-control/sync/worktree-git-owner-target' -import { useWorktreeGitCopyHostId } from '@/lib/worktree-git-copy' -import { useAppStore } from '@/store' +import { useWorktreeGitCopyHostId } from '@/lib/workspace/ownership/worktree-git-copy' +import { useAppStore } from '@/store/index' import type { AppState } from '@/store/types' import { useActiveWorktree } from '@/store/workspaces/selection/use-selected-worktree' import { selectReviewRepositoryForWorkspace } from '@/store/slices/hosted-review/workspace-review-repository' diff --git a/src/renderer/src/components/right-sidebar/folder-workspace-attached-worktrees.ts b/src/renderer/src/components/right-sidebar/folder-workspace-attached-worktrees.ts index d3f4f7fd1d7..169736a8f02 100644 --- a/src/renderer/src/components/right-sidebar/folder-workspace-attached-worktrees.ts +++ b/src/renderer/src/components/right-sidebar/folder-workspace-attached-worktrees.ts @@ -4,7 +4,7 @@ import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folde import { getFolderWorkspaceHostIdentity } from '../../../../shared/folder-workspaces/folder-workspace-worktree' import type { WorkspaceLineage, WorktreeLineage } from '../../../../shared/worktree/lineage-types' import type { Worktree } from '../../../../shared/worktree/types' -import { compareWorktreeDisplayName } from '@/lib/worktree-display-name-order' +import { compareWorktreeDisplayName } from '@/lib/workspace/display/worktree-display-name-order' import { getWorktreeHostIdentity } from '../../../../shared/worktree/host-qualified-identity' import { getProjectedWorktreeLineage } from '../../../../shared/worktree/workspace-lineage-graph' import { diff --git a/src/renderer/src/components/right-sidebar/folder-worktree-section-header.fixture.tsx b/src/renderer/src/components/right-sidebar/folder-worktree-section-header.fixture.tsx index 9d82daa4d4a..d40e0025386 100644 --- a/src/renderer/src/components/right-sidebar/folder-worktree-section-header.fixture.tsx +++ b/src/renderer/src/components/right-sidebar/folder-worktree-section-header.fixture.tsx @@ -36,6 +36,7 @@ function Cards() { expanded onToggle={() => {}} onOpen={() => {}} + actionsSlotRef={() => {}} />
@@ -48,6 +49,7 @@ function Cards() { expanded onToggle={() => {}} onOpen={() => {}} + actionsSlotRef={() => {}} /> @@ -59,6 +61,7 @@ function Cards() { expanded={false} onToggle={() => {}} onOpen={() => {}} + actionsSlotRef={() => {}} />
@@ -82,6 +85,7 @@ export const narrow = defineFixture({ expanded={false} onToggle={() => {}} onOpen={() => {}} + actionsSlotRef={() => {}} />
diff --git a/src/renderer/src/components/right-sidebar/folder-worktree-section-header.tsx b/src/renderer/src/components/right-sidebar/folder-worktree-section-header.tsx index 6df52b72b5d..66641f4b678 100644 --- a/src/renderer/src/components/right-sidebar/folder-worktree-section-header.tsx +++ b/src/renderer/src/components/right-sidebar/folder-worktree-section-header.tsx @@ -15,8 +15,31 @@ type FolderWorktreeSectionHeaderProps = { behind?: number changeCount: number expanded: boolean + showBranchInHeader?: boolean + actions?: React.ReactNode onToggle: () => void onOpen: () => void + /** Receives the embedded panel's filter and overflow buttons while expanded. */ + actionsSlotRef: (element: HTMLDivElement | null) => void +} + +function AheadBehind({ ahead, behind }: { ahead?: number; behind?: number }): React.JSX.Element { + return ( + <> + {!!ahead && ( + + + {ahead} + + )} + {!!behind && ( + + + {behind} + + )} + + ) } export function FolderWorktreeSectionHeader({ @@ -27,86 +50,101 @@ export function FolderWorktreeSectionHeader({ behind, changeCount, expanded, + showBranchInHeader = !expanded, + actions, onToggle, - onOpen + onOpen, + actionsSlotRef }: FolderWorktreeSectionHeaderProps): React.JSX.Element { const t = useTranslate() const openLabel = t( 'auto.components.rightSidebar.FolderWorkspaceSourceControl.openWorktree', 'Open this worktree' ) + const showWorktreeName = !!worktreeName && worktreeName !== branch + // Expanded cards show the branch once, in the body's picker; collapsed cards have no body. + const showSummaryRow = showBranchInHeader && (!!branch || !!ahead || !!behind || changeCount > 0) return ( // Pinned within its own card, above the panel's sticky COMMITS dock.
- + + + + + {openLabel} + + + {expanded && ( + + + + )} +
+ {actions} +
+
+ {showSummaryRow && ( + + {branch && ( + + + + {branch} + )} - - {(branch || !!ahead || !!behind) && ( - - {branch && ( - - - {branch} - - )} - {!!ahead && ( - - - {ahead} - - )} - {!!behind && ( - - - {behind} + + {!expanded && } + {!expanded && changeCount > 0 && ( + + {t( + 'auto.components.rightSidebar.FolderWorkspaceSourceControl.changeCount', + '{{count}} changes', + { count: changeCount, defaultValue_one: '{{count}} change' } + )} )} - )} - - - - - - {openLabel} - + + )}
) } diff --git a/src/renderer/src/components/right-sidebar/hosted-review/creation/use-create-pull-request-field-generation.ts b/src/renderer/src/components/right-sidebar/hosted-review/creation/use-create-pull-request-field-generation.ts index 3f5a0f760cb..b0840a271b9 100644 --- a/src/renderer/src/components/right-sidebar/hosted-review/creation/use-create-pull-request-field-generation.ts +++ b/src/renderer/src/components/right-sidebar/hosted-review/creation/use-create-pull-request-field-generation.ts @@ -1,4 +1,4 @@ -import { textGenerationErrorText } from '@/lib/text-generation-error-copy' +import { textGenerationErrorText } from '@/lib/text-generation/text-generation-error-copy' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' import { useCallback, useEffect, type Dispatch, type RefObject, type SetStateAction } from 'react' diff --git a/src/renderer/src/components/right-sidebar/hosted-review/folder-checks/parent-pr-checks-refresh.ts b/src/renderer/src/components/right-sidebar/hosted-review/folder-checks/parent-pr-checks-refresh.ts index 58a059f9ab4..04e5ebe10a8 100644 --- a/src/renderer/src/components/right-sidebar/hosted-review/folder-checks/parent-pr-checks-refresh.ts +++ b/src/renderer/src/components/right-sidebar/hosted-review/folder-checks/parent-pr-checks-refresh.ts @@ -5,7 +5,7 @@ import type { Worktree } from '../../../../../../shared/worktree/types' import type { HostedReviewInfo } from '../../../../../../shared/source-control/hosted-review/hosted-review-contracts' import { isFolderRepo } from '../../../../../../shared/repo-kind' import { getWorktreeGitIdentityDisplay } from '../../../../../../shared/worktree/git-identity-display' -import { compareWorktreeDisplayName } from '@/lib/worktree-display-name-order' +import { compareWorktreeDisplayName } from '@/lib/workspace/display/worktree-display-name-order' import { getParentPrChecksRefreshIdentity } from './parent-pr-checks-rows' import type { ParentPrChecksRefreshOutcome } from './parent-pr-checks-row-types' diff --git a/src/renderer/src/components/right-sidebar/index.tsx b/src/renderer/src/components/right-sidebar/index.tsx index a43028802d4..059a4cfac24 100644 --- a/src/renderer/src/components/right-sidebar/index.tsx +++ b/src/renderer/src/components/right-sidebar/index.tsx @@ -22,7 +22,7 @@ import { useMeasuredWidth } from './right-sidebar-measured-width' import { isPairedWebClientWindow, shouldRenderDesktopWindowChrome -} from '@/lib/desktop-window-chrome' +} from '@/app-shell/chrome/desktop-window-chrome' import { getRendererAppPlatform } from '@/app-shell/platform/renderer-app-platform' import { ActivityBarPositionMenu, useActivityBarContextPlugin } from './activity-bar-position-menu' import { RightSidebarTopActivityBar } from './right-sidebar-top-activity-bar' diff --git a/src/renderer/src/components/right-sidebar/source-control/ai/section-agent-placement.ts b/src/renderer/src/components/right-sidebar/source-control/ai/section-agent-placement.ts index e7f4a0d1f99..88f858f7d5e 100644 --- a/src/renderer/src/components/right-sidebar/source-control/ai/section-agent-placement.ts +++ b/src/renderer/src/components/right-sidebar/source-control/ai/section-agent-placement.ts @@ -1,7 +1,7 @@ import { toast } from 'sonner' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { translate } from '@/i18n/i18n' -import { resolveWorktreeDisplayName } from '@/lib/worktree-default-display-name' +import { resolveWorktreeDisplayName } from '@/lib/workspace/display/worktree-default-display-name' import { workspaceNavigationToastAction } from '@/lib/workspace/activation/workspace-navigation-toast-action' import type { ExecutionHostId } from '../../../../../../shared/execution-host' import { resolveOwner } from '@/lib/workspace/ownership/resolve-owner' diff --git a/src/renderer/src/components/right-sidebar/source-control/ai/text-generation-dialog.tsx b/src/renderer/src/components/right-sidebar/source-control/ai/text-generation-dialog.tsx index c26c4c4d07d..50b6949f427 100644 --- a/src/renderer/src/components/right-sidebar/source-control/ai/text-generation-dialog.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/ai/text-generation-dialog.tsx @@ -1,4 +1,4 @@ -import { textGenerationErrorText } from '@/lib/text-generation-error-copy' +import { textGenerationErrorText } from '@/lib/text-generation/text-generation-error-copy' import React, { useMemo } from 'react' import { TriangleAlert } from 'lucide-react' import { diff --git a/src/renderer/src/components/right-sidebar/source-control/branches/WorkspaceBranchPicker.tsx b/src/renderer/src/components/right-sidebar/source-control/branches/WorkspaceBranchPicker.tsx index 1c8b31c724f..9a9c02052cb 100644 --- a/src/renderer/src/components/right-sidebar/source-control/branches/WorkspaceBranchPicker.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/branches/WorkspaceBranchPicker.tsx @@ -3,9 +3,9 @@ import { toast } from 'sonner' import { basename } from '@/lib/path' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import type { AppState } from '@/store/types' -import { worktreeGitCopyHostId } from '@/lib/worktree-git-copy' +import { worktreeGitCopyHostId } from '@/lib/workspace/ownership/worktree-git-copy' import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' import { getIndexedWorktreeMap } from '@/store/slices/worktrees/listing/worktree-catalog-index' import { diff --git a/src/renderer/src/components/right-sidebar/source-control/branches/use-workspace-copy-status.test.tsx b/src/renderer/src/components/right-sidebar/source-control/branches/use-workspace-copy-status.test.tsx index e1091af64c5..4bb68f659d1 100644 --- a/src/renderer/src/components/right-sidebar/source-control/branches/use-workspace-copy-status.test.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/branches/use-workspace-copy-status.test.tsx @@ -12,8 +12,8 @@ import type { ExecutionHostId } from '../../../../../../shared/execution-host' import { useAppStore } from '@/store/index' import { useWorkspaceCopyStatus, type WorkspaceCopyStatus } from './use-workspace-copy-status' import { recordWorktreeBranchSwitchLanded } from './workspace-branch-switch-status' -import { resolveWorktreeGitCopyNow } from '@/lib/worktree-git-copy' -import { refreshGitStatusForWorktree } from '../sync/git-status-refresh' +import '@/lib/workspace/ownership/worktree-git-copy' +import '../sync/git-status-refresh' // The same project at the same path on this machine and on an SSH host share one status slot. const id = 'repo1::/srv/ai-tools' @@ -123,14 +123,6 @@ it("reads a twin's own status instead of the selected copy's slot", async () => expect(useAppStore.getState().gitStatusHeadByWorktree[id]).toBe('bbb') }) -it('keeps a hostless local selection from claiming the slot for either copy', async () => { - useAppStore.setState({ activeWorkspaceExecutionHostId: null }) - const seen = await readFor('ssh:box-b') - expect(seen.current).toMatchObject({ statusKnown: true, entries: [] }) - expect(status).toHaveBeenCalledWith(expect.objectContaining({ connectionId: 'box-b' })) - expect(useAppStore.getState().gitStatusByWorktree[id]).toEqual(dirty) -}) - it('drops an open-time refresh that lands after the user selects the twin', async () => { useAppStore.setState({ activeWorkspaceExecutionHostId: 'local', @@ -176,50 +168,6 @@ it("doesn't trust the twin's slot when this copy becomes the owner", async () => expect(seen.current).toMatchObject({ statusKnown: true, entries: [] }) }) -it("shows the copy's own status when an identical newer poll supersedes the picker refresh", async () => { - // Both copies clean at the same commit; the store keeps the same entries reference for an identical status. - useAppStore.setState({ - gitStatusByWorktree: { [id]: [] }, - gitStatusHeadByWorktree: { [id]: 'aaa' } - }) - const seen: { current: WorkspaceCopyStatus | null } = { current: null } - function Probe({ open }: { open: boolean }) { - seen.current = useWorkspaceCopyStatus({ - worktreeId: id, - worktreePath: path, - hostId: 'local', - open, - refreshOnOpen: true - }) - return null - } - await act(async () => root.render()) - await act(async () => useAppStore.setState({ activeWorkspaceExecutionHostId: 'local' })) - const finishPicker = deferStatus() - await act(async () => root.render()) - const target = resolveWorktreeGitCopyNow(id, 'local') - if (!target) { - throw new Error('Local copy unresolved') - } - const state = useAppStore.getState() - await act(async () => - refreshGitStatusForWorktree({ - target: target.transport, - ownerHostId: target.hostId, - worktreeId: id, - worktreePath: path, - deps: { - setGitStatus: state.setGitStatus, - updateWorktreeGitIdentity: state.updateWorktreeGitIdentity, - setUpstreamStatus: state.setUpstreamStatus, - fetchUpstreamStatus: async () => null - } - }) - ) - await finishPicker(clean) - expect(seen.current).toMatchObject({ statusKnown: true, entries: [] }) -}) - it("keeps the twin's status out after selecting it and back while a refresh is in flight", async () => { useAppStore.setState({ activeWorkspaceExecutionHostId: 'local', diff --git a/src/renderer/src/components/right-sidebar/source-control/branches/use-workspace-copy-status.ts b/src/renderer/src/components/right-sidebar/source-control/branches/use-workspace-copy-status.ts index 0823f9087d4..6d1d1038dda 100644 --- a/src/renderer/src/components/right-sidebar/source-control/branches/use-workspace-copy-status.ts +++ b/src/renderer/src/components/right-sidebar/source-control/branches/use-workspace-copy-status.ts @@ -1,7 +1,7 @@ import { useEffect, useState } from 'react' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { translate } from '@/i18n/i18n' -import { resolveWorktreeGitCopyNow } from '@/lib/worktree-git-copy' +import { resolveWorktreeGitCopyNow } from '@/lib/workspace/ownership/worktree-git-copy' import { getRuntimeGitStatus } from '@/runtime/source-control/git/runtime-git-status-client' import type { ExecutionHostId } from '../../../../../../shared/execution-host' import type { diff --git a/src/renderer/src/components/right-sidebar/source-control/branches/workspace-branch-switch-status.ts b/src/renderer/src/components/right-sidebar/source-control/branches/workspace-branch-switch-status.ts index 8e70a32a1dd..7e7dadfde3e 100644 --- a/src/renderer/src/components/right-sidebar/source-control/branches/workspace-branch-switch-status.ts +++ b/src/renderer/src/components/right-sidebar/source-control/branches/workspace-branch-switch-status.ts @@ -1,10 +1,10 @@ -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import type { AppState } from '@/store/types' import { resolveWorktreeGitCopyNow, worktreeCopyPushTarget, worktreeGitCopyHostId -} from '@/lib/worktree-git-copy' +} from '@/lib/workspace/ownership/worktree-git-copy' import type { ExecutionHostId } from '../../../../../../shared/execution-host' import { clearLandedBranchSwitchError, diff --git a/src/renderer/src/components/right-sidebar/source-control/commit/use-commit-message-generation.ts b/src/renderer/src/components/right-sidebar/source-control/commit/use-commit-message-generation.ts index 0da639efec5..49905bebfb5 100644 --- a/src/renderer/src/components/right-sidebar/source-control/commit/use-commit-message-generation.ts +++ b/src/renderer/src/components/right-sidebar/source-control/commit/use-commit-message-generation.ts @@ -6,16 +6,19 @@ import { } from '../panel/worktree-scope' import { resolveSourceControlAiEnabled } from '../../../../../../shared/source-control/ai/source-control-ai-operation-policy' import { resolveSourceControlAiForOperation } from '../../../../../../shared/source-control/ai/source-control-ai-operation-resolution' -import { getRuntimeGitRepoDiscoveryHostKey } from '@/runtime/source-control/git/runtime-git-client-context' -import { textGenerationCopyText } from '@/lib/text-generation-error-copy' +import { + getRuntimeGitRepoDiscoveryHostKey, + type RuntimeGenerateCommitMessageOverrides +} from '@/runtime/source-control/git/runtime-git-client-context' +import { textGenerationCopyText } from '@/lib/text-generation/text-generation-error-copy' import { useCallback, useEffect } from 'react' import { useStore } from 'zustand' import { cancelRuntimeGenerateCommitMessage, generateRuntimeCommitMessage } from '@/runtime/source-control/git/runtime-git-generation-client' -import type { RuntimeGenerateCommitMessageOverrides } from '@/runtime/source-control/git/runtime-git-client-context' -import { useAppStore } from '@/store' + +import { useAppStore } from '@/store/index' import { createRunningCommitMessageGenerationRecord, getCommitMessageGenerationRecordKey, diff --git a/src/renderer/src/components/right-sidebar/source-control/listing/section-header.tsx b/src/renderer/src/components/right-sidebar/source-control/listing/section-header.tsx index e6b95041d57..00a38832642 100644 --- a/src/renderer/src/components/right-sidebar/source-control/listing/section-header.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/listing/section-header.tsx @@ -3,6 +3,7 @@ import { ChevronDown } from 'lucide-react' import { cn } from '@/lib/class-names' import { Button } from '@/components/ui/button' import { useTranslate } from '@/i18n/use-translate' +import { useSourceControlScope } from '../panel/worktree-scope' export function SectionHeader({ label, @@ -23,22 +24,27 @@ export function SectionHeader({ actions?: React.ReactNode }): React.JSX.Element { const t = useTranslate() + // Folder cards keep the gap above the first file equal to the one below the last. + const compact = useSourceControlScope() !== null // Share the rounded container so hover styling spans the whole row. return ( -
+
-
{actions}
+
+ {actions} +
) diff --git a/src/renderer/src/components/right-sidebar/source-control/listing/sequencer-recovery-controls.test.tsx b/src/renderer/src/components/right-sidebar/source-control/listing/sequencer-recovery-controls.test.tsx deleted file mode 100644 index 95849f0b337..00000000000 --- a/src/renderer/src/components/right-sidebar/source-control/listing/sequencer-recovery-controls.test.tsx +++ /dev/null @@ -1,145 +0,0 @@ -// @vitest-environment happy-dom -import { act } from 'react' -import { createRoot } from 'react-dom/client' -import { expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' -import { SequencerRecoveryControls } from './sequencer-recovery-controls' -import '@/lib/source-control/graph/git-graph-tab' -import { GIT_GRAPH_REFRESH_EVENT } from '@/lib/source-control/graph/git-graph-refresh-event' -import { local } from '@/components/editor/git-graph/git-graph-workspace.test-fixtures' -import type * as WorktreeGitCopy from '@/lib/worktree-git-copy' -import type { GitStatusResult } from '../../../../../../shared/git/status/git-status-types' - -const { status, continued } = vi.hoisted(() => ({ status: vi.fn(), continued: vi.fn() })) -vi.mock('@/runtime/source-control/git/runtime-git-commit-actions-client', () => ({ - sequencerContinueRuntimeGit: continued -})) -vi.mock('@/runtime/source-control/git/runtime-git-status-client', () => ({ - getRuntimeGitStatus: status -})) -vi.mock('@/runtime/source-control/git/git-commit-actions-capability', () => ({ - useGitCommitActionsSupport: () => ({ supported: true }), - gitCommitActionsSupported: async () => true -})) -vi.mock('@/components/confirmation-dialog-context', () => ({ - useConfirmationDialog: () => async () => true -})) -vi.mock('./use-worktree-context', () => ({ - useSourceControlWorktreeContext: () => ({ activeWorktreeId: 'r::/repo', worktreePath: '/repo' }) -})) -vi.mock('@/lib/worktree-git-copy', async (importOriginal) => ({ - ...(await importOriginal()), - resolveWorktreeGitCopyNow: () => ({ - worktreeId: 'r::/repo', - hostId: useAppStore.getState().activeWorkspaceExecutionHostId, - transport: { kind: 'local' }, - connectionId: undefined - }) -})) - -it('fences late recovery status while invalidating the original graph after navigation', async () => { - const initial = useAppStore.getState() - const pending = Promise.withResolvers() - const fetching = Promise.withResolvers() - let accepted: GitStatusResult = { entries: [], head: 'host-A', conflictOperation: 'cherry-pick' } - const refreshed = Promise.withResolvers() - let requestedPublishTarget: unknown - let acceptedUpstream: unknown - useAppStore.setState({ - worktreesByRepo: { - r: [ - { ...local, pushTarget: { remoteName: 'publish-a', branchName: 'topic-a' } }, - { - ...local, - hostId: 'ssh:B', - pushTarget: { remoteName: 'publish-b', branchName: 'topic-b' } - } - ] - }, - activeWorktreeId: 'r::/repo', - activeWorkspaceExecutionHostId: 'local', - setGitStatus: (_id, result) => { - accepted = result - }, - updateWorktreeGitIdentity: () => {}, - fetchUpstreamStatus: async (_id, _path, _connectionId, pushTarget) => { - requestedPublishTarget = pushTarget - return { hasUpstream: true, ahead: 2, behind: 0 } - }, - setUpstreamStatus: (_id, upstream) => { - acceptedUpstream = upstream - refreshed.resolve() - } - }) - status.mockImplementation(() => { - fetching.resolve() - return pending.promise - }) - continued.mockResolvedValue(undefined) - const container = document.createElement('div') - document.body.append(container) - const root = createRoot(container) - let invalidatedWorktree: unknown - const onGraphRefresh = (event: Event) => { - if (event instanceof CustomEvent) { - invalidatedWorktree = event.detail - } - } - try { - await act(async () => - root.render( - - ) - ) - await act(async () => { - container.querySelector('button')!.click() - await fetching.promise - }) - await act(async () => useAppStore.setState({ activeWorkspaceExecutionHostId: 'ssh:B' })) - accepted = { entries: [], head: 'host-B', conflictOperation: 'revert' } - await act(async () => { - pending.resolve({ entries: [], head: 'host-A-clean', conflictOperation: 'unknown' }) - await pending.promise - }) - expect(accepted).toEqual({ entries: [], head: 'host-B', conflictOperation: 'revert' }) - - const recovering = Promise.withResolvers() - const started = Promise.withResolvers() - continued.mockImplementation(() => { - started.resolve() - return recovering.promise - }) - window.addEventListener(GIT_GRAPH_REFRESH_EVENT, onGraphRefresh) - await act(async () => { - container.querySelector('button')!.click() - await started.promise - }) - await act(async () => useAppStore.setState({ activeWorktreeId: 'other' })) - await act(async () => { - recovering.resolve() - await recovering.promise - }) - expect(invalidatedWorktree).toBe('r::/repo') - expect(accepted).toEqual({ entries: [], head: 'host-B', conflictOperation: 'revert' }) - - status.mockResolvedValue({ - entries: [], - head: 'host-B-clean', - conflictOperation: 'unknown', - upstreamStatus: { hasUpstream: true, ahead: 99, behind: 0 } - }) - continued.mockResolvedValue(undefined) - await act(async () => useAppStore.setState({ activeWorktreeId: 'r::/repo' })) - await act(async () => { - container.querySelector('button')!.click() - await refreshed.promise - }) - expect(requestedPublishTarget).toEqual({ remoteName: 'publish-b', branchName: 'topic-b' }) - expect(acceptedUpstream).toEqual({ hasUpstream: true, ahead: 2, behind: 0 }) - } finally { - window.removeEventListener(GIT_GRAPH_REFRESH_EVENT, onGraphRefresh) - await act(async () => root.unmount()) - container.remove() - useAppStore.setState(initial, true) - } -}) diff --git a/src/renderer/src/components/right-sidebar/source-control/listing/sequencer-recovery-controls.tsx b/src/renderer/src/components/right-sidebar/source-control/listing/sequencer-recovery-controls.tsx index c6692b52cca..873c6095bbc 100644 --- a/src/renderer/src/components/right-sidebar/source-control/listing/sequencer-recovery-controls.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/listing/sequencer-recovery-controls.tsx @@ -18,7 +18,10 @@ import { extractIpcErrorMessage } from '@/runtime/errors/ipc-error' import { useSourceControlWorktreeContext } from './use-worktree-context' import type { GitCommitAction } from '../../../../../../shared/git/commands/git-commit-action' import { useAppStore } from '@/store/index' -import { resolveWorktreeGitCopyNow, worktreeCopyPushTarget } from '@/lib/worktree-git-copy' +import { + resolveWorktreeGitCopyNow, + worktreeCopyPushTarget +} from '@/lib/workspace/ownership/worktree-git-copy' async function runSequencerRecovery(run: () => Promise, refresh: () => void) { try { diff --git a/src/renderer/src/components/right-sidebar/source-control/listing/uncommitted-sections.tsx b/src/renderer/src/components/right-sidebar/source-control/listing/uncommitted-sections.tsx index c80dea85b36..6c77ceaf81a 100644 --- a/src/renderer/src/components/right-sidebar/source-control/listing/uncommitted-sections.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/listing/uncommitted-sections.tsx @@ -14,6 +14,7 @@ import { import { ActionButton } from './action-button' import { SectionHeader } from './section-header' import { SourceControlSectionFileList } from './section-file-list' +import { useSourceControlScope } from '../panel/worktree-scope' import { getSourceControlSectionViewAction, type SourceControlDisplaySection, @@ -89,6 +90,7 @@ export function SourceControlUncommittedSections(props: { requestDiscardEntry: (entry: GitStatusEntry) => void diffCommentCountByPath: Map }): React.JSX.Element { + const embedded = useSourceControlScope() !== null const t = useTranslate() return ( <> @@ -176,35 +178,37 @@ export function SourceControlUncommittedSections(props: { } /> {!isCollapsed && ( - +
+ +
)}
) diff --git a/src/renderer/src/components/right-sidebar/source-control/listing/use-selection.ts b/src/renderer/src/components/right-sidebar/source-control/listing/use-selection.ts index 9888f31b182..9cc0b17c0d0 100644 --- a/src/renderer/src/components/right-sidebar/source-control/listing/use-selection.ts +++ b/src/renderer/src/components/right-sidebar/source-control/listing/use-selection.ts @@ -190,7 +190,8 @@ export function useSourceControlSelection({ return } - const container = containerRef.current + const panel = containerRef.current + const container = panel?.closest('[data-source-control-worktree]') ?? panel const target = e.target if (!container || !(target instanceof Node) || container.contains(target)) { return diff --git a/src/renderer/src/components/right-sidebar/source-control/panel/branch-context-row.tsx b/src/renderer/src/components/right-sidebar/source-control/panel/branch-context-row.tsx index af4712d35a9..940a009f98c 100644 --- a/src/renderer/src/components/right-sidebar/source-control/panel/branch-context-row.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/panel/branch-context-row.tsx @@ -103,6 +103,7 @@ export function SourceControlBranchContextRow({ headControl, manualReviewUrl, branchLineTotal, + reviewControl, onChangeBaseRef, onRetry }: { @@ -112,6 +113,7 @@ export function SourceControlBranchContextRow({ headControl?: React.ReactNode manualReviewUrl?: string | null branchLineTotal?: GitBranchLineTotal | null + reviewControl?: React.ReactNode onChangeBaseRef: () => void onRetry: () => void }): React.JSX.Element | null { @@ -124,8 +126,11 @@ export function SourceControlBranchContextRow({ return null } return ( -
- {headControl ?? } +
+ + {headControl ?? } + + {reviewControl}
) } @@ -159,7 +164,12 @@ export function SourceControlBranchContextRow({ onChangeBaseRef={onChangeBaseRef} changeBaseTitle={changeBaseTitle} leading={