diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index f5cd4b15a0f..4560549f0d2 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -1242,7 +1242,7 @@ 3 test-no-wall-clock:src/main/runtime/orca-runtime-codex-idle-title-chat-address.test.ts 3 test-no-wall-clock:src/main/runtime/orchestration-cli-subprocess.test.ts 3 test-no-wall-clock:src/main/runtime/rpc/methods/orchestration/worker/fleet-status-terminal-identity.test.ts -3 test-no-wall-clock:src/main/runtime/workspace-layout-live-titles.test.ts +2 test-no-wall-clock:src/main/runtime/workspace-layout-live-titles.test.ts 3 test-no-wall-clock:src/main/star-nag/service-threshold-prompt.test.ts 3 test-no-wall-clock:src/main/windows/windows-msys-job.win32.test.ts 3 test-no-wall-clock:src/main/wsl/orcad/wsl-orcad-real-distro-lane.test.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index b70aec7ac62..1715d3d918c 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -2710,9 +2710,9 @@ "surfaces": ["headless terminal output ingestion", "terminal snapshot continuity"], "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "ssh", "remote-runtime"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["local", "daemon", "ssh", "remote-runtime"], - "coverageNotes": "Shared parser, production emulator and Session contracts cover local/daemon paths; remote snapshot semantics use the existing corruption reproduction without live transport. The scanner has no workspace or host branching; folder/git workspaces, WSL, mobile/relay and platform execution/wire boundaries are unchanged.", + "coveredPlatforms": ["macos", "linux"], + "coveredProviders": [], + "coverageNotes": "Shared parser, production emulator and Session contracts cover local/daemon paths; remote snapshot semantics use the existing corruption reproduction without live transport. The scanner has no workspace or host branching; folder/git workspaces, WSL, mobile/relay and platform execution/wire boundaries are unchanged. Audit1356 removes the two remote-snapshot mouse-reset cases: their test-owned replay helper appends the production reset constant and cannot catch an actual consumer omitting reset. Their mode-serialization/reset alarms are intentionally lost. The split escape-tail serialization and xterm continuation case remains, with no live remote transport claim. The complete prior mixed 15-test receipt is historical and cannot validate this reduced source; fresh validation remains required. Audit1365: focused Linux unit selection passed on source head 8880357cb420c45f1b808ae545a5bc609324624d. This new result has its own exact command; historical results keep their prior scope. Intentional test losses remain recorded in knownGaps. No physical-provider, native input, rendered E2E, p95, soak or replacement-coverage claim.", "motivatingLinks": ["https://github.com/stablyai/orca/issues/7329"], "invariant": "Partial escape tracking preserves exact pending UTF-16 and completion across chunk/snapshot boundaries while skipping ordinary ground-state text without a JavaScript per-code-unit walk.", "oracle": "Colored ASCII and UTF-16 output retains the exact incomplete CSI tail using fewer than 32 code-unit inspections. Every split of CSI/OSC/DCS/ESC-intermediate controls and CAN/SUB/ESC aborts preserve completion; one-character echo performs zero inspections or native ESC searches. Seeded headless snapshot restore matches a renderer terminal twin.", @@ -2752,13 +2752,14 @@ "summary": "82 tests passed across four files including 593,468 fold-fuzz cases." }, { - "date": "2026-09-07", + "date": "2026-11-04", "runner": "local", - "platform": "macos", - "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts src/main/daemon/session-shell-recovery.test.ts src/main/daemon/headless-emulator-fidelity.fuzz.test.ts", + "platform": "linux", + "command": "pnpm --config.verifyDepsBeforeRun=false exec vitest run --config config/vitest.config.ts src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts src/main/daemon/session-shell-recovery.test.ts src/main/daemon/headless-emulator-fidelity.fuzz.test.ts --maxWorkers=2", "result": "passed", - "durationSeconds": 36.24, - "summary": "15 tests passed across three files including 300 headless-to-renderer snapshot fidelity streams." + "durationSeconds": 3.32, + "summary": "Test Files 3 passed (3); Tests 11 passed (11). Source head 8880357cb420c45f1b808ae545a5bc609324624d. Focused current retained command; no live provider/native input/soak/benchmark or removed-case equivalence claim. Node24.22.0 with ORCA_BACKGROUND_LAUNCH=1 and an isolated Xvfb display.", + "currentCommand": "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts src/main/daemon/session-shell-recovery.test.ts src/main/daemon/headless-emulator-fidelity.fuzz.test.ts" } ], "runtimeBudget": { @@ -2779,7 +2780,10 @@ }, "knownGaps": [ "No launched Electron or live SSH/WSL/Windows/Linux process, native input or end-to-end UI-latency measurement.", - "Existing 4,096-code-unit tracking abandonment and idle-death partial-tail behavior are unchanged." + "Existing 4,096-code-unit tracking abandonment and idle-death partial-tail behavior are unchanged.", + "Audit1356 removes the two remote-snapshot mouse-reset cases: their test-owned replay helper appends the production reset constant and cannot catch an actual consumer omitting reset. Their mode-serialization/reset alarms are intentionally lost. The split escape-tail serialization and xterm continuation case remains, with no live remote transport claim. The complete prior mixed 15-test receipt is historical and cannot validate this reduced source; fresh validation remains required.", + "Audit1365 retires this complete dated receipt because its selector includes a deleted or reduced source. It does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-09-07\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts src/main/daemon/session-shell-recovery.test.ts src/main/daemon/headless-emulator-fidelity.fuzz.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 36.24,\n \"summary\": \"15 tests passed across three files including 300 headless-to-renderer snapshot fidelity streams.\"\n }", + "Audit1365 historical provider claim before source reduction: [\"local\",\"daemon\",\"ssh\",\"remote-runtime\"]. Remaining unchanged-source receipts do not explicitly map provider execution; coveredProviders is cleared." ], "promotionCriteria": [ "Complete CI soak with zero unexplained flakes and preserve the observable oracle." @@ -3047,19 +3051,20 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "wsl", "ssh", "remote-runtime"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["local", "daemon", "wsl"], - "coverageNotes": "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): macOS daemon-backed Electron journey verifies same PID and terminal identity plus rendered output. Focused renderer contracts pass on Linux, Windows and WSL. Neighboring SSH model and replay contracts pass locally; no new live SSH or paired-runtime journey. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-unanswered-command-finish.spec.ts removed. Unanswered SSH shell finish keeps/drops mocked agent row matrix disappears. src/renderer/src/components/terminal-pane/pty-connection-split-cwd-resolution.test.ts reduced. Happy inherited-cwd wait and transport-option forwarding sample loses its individual alarm. src/renderer/src/components/terminal-pane/pty-connection-command-input-agent-identity.spec.ts removed. Typed Droid versus process/launch identity and SSH/runtime process-evidence matrices disappear. src/renderer/src/components/terminal-pane/pty-connection/reattach-success-settle.test.ts removed. Success/no-ID/expired/superseded attach-settlement bag alarms disappear. src/renderer/src/components/terminal-pane/pty-transport-user-input.test.ts reduced. Every-write kind forwarding and synchronous driving-attempt observer/rejection/ACK call counts disappear. src/renderer/src/components/terminal-pane/pty-connection-codex-restart-input-lookup.spec.ts removed. No global tab enumeration on ordinary/stale input and known restart notice input-block mock-call alarms. src/renderer/src/components/terminal-pane/pty-connection-layout-owner-wake.test.ts removed. Hidden-to-visible single-pane start request, attach-only argument and negative local wake-record alarms are intentionally dropped; no real server wake/ack occurs. 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. src/renderer/src/components/terminal-pane/pty-connection-command-finished-cleanup.spec.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. src/renderer/src/components/terminal-pane/pty-connection-terminal-input-gating.spec.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.", + "coveredPlatforms": ["macos", "linux"], + "coveredProviders": [], + "coverageNotes": "Audit1361 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): macOS daemon-backed Electron journey verifies same PID and terminal identity plus rendered output. Focused renderer contracts pass on Linux, Windows and WSL. Neighboring SSH model and replay contracts pass locally; no new live SSH or paired-runtime journey. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-unanswered-command-finish.spec.ts removed. Unanswered SSH shell finish keeps/drops mocked agent row matrix disappears. src/renderer/src/components/terminal-pane/pty-connection-split-cwd-resolution.test.ts reduced. Happy inherited-cwd wait and transport-option forwarding sample loses its individual alarm. src/renderer/src/components/terminal-pane/pty-connection-command-input-agent-identity.spec.ts removed. Typed Droid versus process/launch identity and SSH/runtime process-evidence matrices disappear. src/renderer/src/components/terminal-pane/pty-connection/reattach-success-settle.test.ts removed. Success/no-ID/expired/superseded attach-settlement bag alarms disappear. src/renderer/src/components/terminal-pane/pty-transport-user-input.test.ts reduced. Every-write kind forwarding and synchronous driving-attempt observer/rejection/ACK call counts disappear. src/renderer/src/components/terminal-pane/pty-connection-codex-restart-input-lookup.spec.ts removed. No global tab enumeration on ordinary/stale input and known restart notice input-block mock-call alarms. src/renderer/src/components/terminal-pane/pty-connection-layout-owner-wake.test.ts removed. Hidden-to-visible single-pane start request, attach-only argument and negative local wake-record alarms are intentionally dropped; no real server wake/ack occurs. 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. src/renderer/src/components/terminal-pane/pty-connection-command-finished-cleanup.spec.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. src/renderer/src/components/terminal-pane/pty-connection-terminal-input-gating.spec.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. Audit1361: src/renderer/src/components/terminal-pane/pty-connection/foreground-output-scan.test.ts reduced. Internal searched-character budget and ordinary/malformed no-op controls. No equivalent replacement coverage is claimed. Audit1365: focused Linux unit selection passed on source head 8880357cb420c45f1b808ae545a5bc609324624d. This new result has its own exact command; historical results keep their prior scope. Intentional test losses remain recorded in knownGaps. No physical-provider, native input, rendered E2E, p95, soak or replacement-coverage claim.", "motivatingLinks": [ "https://github.com/user-attachments/assets/e8c6d1dc-6150-4c3d-b55a-3d12efefdd04", "https://github.com/user-attachments/assets/b0328f88-34ac-4d51-8119-9efe17072435" ], "invariant": "Adopting a prestarted terminal preserves its existing process and paints snapshot-covered startup output once while retaining subsequent live output. Missing sequence proof or blank snapshots must not authorize dropping output.", - "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): Pass snapshot sequence and proven zero keyboard flags through real IPC transport projection. Deliver snapshot-covered and newer output before reattach resolves; drain replay parse callbacks and require one startup marker and the newer output. Repeat with no sequence and blank snapshot to retain unproven bytes. In Electron select a prestarted workspace, type a generated marker and compare PID and stable terminal identities before and after.", + "oracle": "The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Pass snapshot sequence and proven zero keyboard flags through real IPC transport projection. Deliver snapshot-covered and newer output before reattach resolves; drain replay parse callbacks and require one startup marker and the newer output. Repeat with no sequence and blank snapshot to retain unproven bytes. In Electron select a prestarted workspace, type a generated marker and compare PID and stable terminal identities before and after.", "commands": [ "pnpm test src/renderer/src/components/terminal-pane/pty-transport-connect-spawn.test.ts src/renderer/src/components/terminal-pane/pty-connection-hidden-replay.test.ts", "pnpm test src/renderer/src/components/terminal-pane/pty-transport-connect-spawn.test.ts src/renderer/src/components/terminal-pane/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection-visibility-and-exit.test.ts", - "pnpm test src/renderer/src/components/terminal-pane/pty-connection src/renderer/src/components/terminal-pane/pty-transport" + "pnpm test src/renderer/src/components/terminal-pane/pty-connection src/renderer/src/components/terminal-pane/pty-transport", + "pnpm test src/renderer/src/components/terminal-pane/pty-connection/foreground-output-scan.test.ts" ], "testFiles": [ "src/renderer/src/components/terminal-pane/pty-transport-connect-spawn.test.ts", @@ -3091,6 +3096,16 @@ "durationSeconds": 2.34, "summary": "5 suites / 48 tests pass. Focused 2-suite runs independently pass 27 tests on Linux, Windows and WSL.", "currentCommand": "pnpm test src/renderer/src/components/terminal-pane/pty-transport-connect-spawn.test.ts src/renderer/src/components/terminal-pane/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection-visibility-and-exit.test.ts" + }, + { + "date": "2026-11-04", + "runner": "local", + "platform": "linux", + "command": "pnpm --config.verifyDepsBeforeRun=false test src/renderer/src/components/terminal-pane/pty-connection/foreground-output-scan.test.ts --maxWorkers=2", + "result": "passed", + "durationSeconds": 2.31, + "summary": "Test Files 1 passed (1); Tests 3 passed (3). Source head 8880357cb420c45f1b808ae545a5bc609324624d. Focused retained foreground-output scan only, not all directory-selected gate cases or live provider behavior. Node24.22.0 with ORCA_BACKGROUND_LAUNCH=1 and an isolated Xvfb display.", + "currentCommand": "pnpm test src/renderer/src/components/terminal-pane/pty-connection/foreground-output-scan.test.ts" } ], "runtimeBudget": { @@ -3099,15 +3114,15 @@ }, "flakeHistory": { "status": "unknown", - "evidence": "Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: Focused local and remote runs pass; no CI soak history." + "evidence": "Changed selectors have no new soak result after Audit1361; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: Focused local and remote runs pass; no CI soak history." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Metadata tests fail before forwarding. Corrected parse-draining regression observes two startup markers when the baseline installation is removed, and one after restoration. Initial missing-live-output failure was a harness parse-drain omission and is not red proof. Before/fixed Electron screenshots show duplicate/single startup output." + "evidence": "Audit1361 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Metadata tests fail before forwarding. Corrected parse-draining regression observes two startup markers when the baseline installation is removed, and one after restoration. Initial missing-live-output failure was a harness parse-drain omission and is not red proof. Before/fixed Electron screenshots show duplicate/single startup output." }, "performanceBudget": { "required": true, - "evidence": "Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Reuses existing snapshot baseline reconciliation with no new scan, timer or subprocess. Corrected daemon-backed rendered trial reaches replay at 116.6 ms and generated keyboard output at 177 ms after selecting the prestarted workspace. This measures selection/adoption, not ordinary composer creation." + "evidence": "Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Reuses existing snapshot baseline reconciliation with no new scan, timer or subprocess. Corrected daemon-backed rendered trial reaches replay at 116.6 ms and generated keyboard output at 177 ms after selecting the prestarted workspace. This measures selection/adoption, not ordinary composer creation." }, "promotionCriteria": [ "Meet manifest CI and soak policy.", @@ -3120,7 +3135,9 @@ "Mixed-version snapshots without sequence proof intentionally retain legacy behavior.", "Retired during audit1319 selector cleanup; original complete execution receipt (unchanged): {\"date\":\"2026-09-04\",\"runner\":\"local\",\"platform\":\"macos\",\"command\":\"pnpm test src/renderer/src/components/terminal-pane/pty-connection src/renderer/src/components/terminal-pane/pty-transport\",\"result\":\"passed\",\"durationSeconds\":5.67,\"summary\":\"Broader connection/transport gate: 77 files and 813 tests passed, including neighboring restore, reconnect, input and replay behavior. Log: artifacts/worktree-create/orca-draft-replay-broader-gate.log.\"}", "Audit1342: src/renderer/src/components/terminal-pane/pty-connection-unanswered-command-finish.spec.ts removed. Unanswered SSH shell finish keeps/drops mocked agent row matrix disappears. src/renderer/src/components/terminal-pane/pty-connection-split-cwd-resolution.test.ts reduced. Happy inherited-cwd wait and transport-option forwarding sample loses its individual alarm. src/renderer/src/components/terminal-pane/pty-connection-command-input-agent-identity.spec.ts removed. Typed Droid versus process/launch identity and SSH/runtime process-evidence matrices disappear. src/renderer/src/components/terminal-pane/pty-connection/reattach-success-settle.test.ts removed. Success/no-ID/expired/superseded attach-settlement bag alarms disappear. src/renderer/src/components/terminal-pane/pty-transport-user-input.test.ts reduced. Every-write kind forwarding and synchronous driving-attempt observer/rejection/ACK call counts disappear. src/renderer/src/components/terminal-pane/pty-connection-codex-restart-input-lookup.spec.ts removed. No global tab enumeration on ordinary/stale input and known restart notice input-block mock-call alarms. src/renderer/src/components/terminal-pane/pty-connection-layout-owner-wake.test.ts removed. Hidden-to-visible single-pane start request, attach-only argument and negative local wake-record alarms are intentionally dropped; no real server wake/ack occurs. 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. src/renderer/src/components/terminal-pane/pty-connection-command-finished-cleanup.spec.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. src/renderer/src/components/terminal-pane/pty-connection-terminal-input-gating.spec.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.", - "Audit1342 historical platform/provider scope before source changes: {\"coveredPlatforms\":[\"macos\",\"linux\",\"windows\"],\"coveredProviders\":[\"local\",\"daemon\",\"wsl\"]}. Remaining provider scope applies only to unchanged-source receipts." + "Audit1342 historical platform/provider scope before source changes: {\"coveredPlatforms\":[\"macos\",\"linux\",\"windows\"],\"coveredProviders\":[\"local\",\"daemon\",\"wsl\"]}. Remaining provider scope applies only to unchanged-source receipts.", + "Audit1361: src/renderer/src/components/terminal-pane/pty-connection/foreground-output-scan.test.ts reduced. Internal searched-character budget and ordinary/malformed no-op controls. No equivalent replacement coverage is claimed.", + "Audit1361 historical platform/provider scope before source changes: {\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"local\",\"daemon\",\"wsl\"]}. Remaining provider scope applies only to unchanged-source receipts." ], "demotionRule": "Keep experimental or demote if adoption duplicates covered output, drops newer or unproven output, changes terminal ownership, or flakes without explanation." }, @@ -7486,16 +7503,16 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["remote-runtime", "ssh", "wsl"], - "coveredPlatforms": ["macos"], + "coveredPlatforms": ["macos", "linux"], "coveredProviders": [], - "coverageNotes": "Deterministic main-process fakes cover route-Session recognition after logical release, prepared-page renderer ownership, stale and live waiters sharing pending partition setup, generic-policy-before-route-lockdown ordering, blank quarantine, exact guest/renderer/partition/logical-page registration, opaque page-authority replacement, a separate navigation grant, repeated navigation, invalid-scheme denial, dynamic page-authority revocation, popup denial, delayed/failed admission closure, exact page-release closure, retirement-start and destroyed-inspection failure, shared-partition retirement ordering, policy retention until every destroyed acknowledgement, guest process loss/destruction, opaque lifecycle claims across spontaneous destruction and WebContents ID reuse, owning-renderer process loss before, during, and after registration, mutable input isolation, page conflicts, and token-safe destroyed cleanup. The production page-command executor additionally retains an exact execution-host route, prepares its immutable partition, mounts one trusted renderer generation blank, registers and grants its exact guest, loads only normalized HTTP(S), and attempts every safe generation-scoped cleanup after failure, abort, or retirement while holding network resources without destruction proof. A production main-process bridge binds mount and retirement requests to the exact current renderer object and document generation, rejects sender spoofing and WebContents-ID reuse, carries no target URL, bounds pending requests, aborts, timeouts, malformed replies, and lifecycle replacement, and restores only an exact surviving renderer document after blocked or failed provisional navigation. The top-frame preload now queues and validates bounded requests before one replaceable subscriber, while a document-owned renderer registry mounts only blank route webviews, bounds global and per-partition guests, and fences attachment, retirement, destruction, and renderer loss by the full page tuple. Real Electron 43.1.0 proves exact main-frame reply admission, delayed guest-ID readiness, blank attachment, host ownership, destruction, and fail-closed denied attachment. Normal browser Sessions and paired web clients bypass the renderer registry. Production host composition and client placement activate the executor only after capability-gated placement preparation. Process/document swaps, worker/request/download settlement, traffic containment, and provider journeys remain uncovered.", + "coverageNotes": "Audit1363 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 main-process fakes cover route-Session recognition after logical release, prepared-page renderer ownership, stale and live waiters sharing pending partition setup, generic-policy-before-route-lockdown ordering, blank quarantine, exact guest/renderer/partition/logical-page registration, opaque page-authority replacement, a separate navigation grant, repeated navigation, invalid-scheme denial, dynamic page-authority revocation, popup denial, delayed/failed admission closure, exact page-release closure, retirement-start and destroyed-inspection failure, shared-partition retirement ordering, policy retention until every destroyed acknowledgement, guest process loss/destruction, opaque lifecycle claims across spontaneous destruction and WebContents ID reuse, owning-renderer process loss before, during, and after registration, mutable input isolation, page conflicts, and token-safe destroyed cleanup. The production page-command executor additionally retains an exact execution-host route, prepares its immutable partition, mounts one trusted renderer generation blank, registers and grants its exact guest, loads only normalized HTTP(S), and attempts every safe generation-scoped cleanup after failure, abort, or retirement while holding network resources without destruction proof. A production main-process bridge binds mount and retirement requests to the exact current renderer object and document generation, rejects sender spoofing and WebContents-ID reuse, carries no target URL, bounds pending requests, aborts, timeouts, malformed replies, and lifecycle replacement, and restores only an exact surviving renderer document after blocked or failed provisional navigation. The top-frame preload now queues and validates bounded requests before one replaceable subscriber, while a document-owned renderer registry mounts only blank route webviews, bounds global and per-partition guests, and fences attachment, retirement, destruction, and renderer loss by the full page tuple. Real Electron 43.1.0 proves exact main-frame reply admission, delayed guest-ID readiness, blank attachment, host ownership, destruction, and fail-closed denied attachment. Normal browser Sessions and paired web clients bypass the renderer registry. Production host composition and client placement activate the executor only after capability-gated placement preparation. Process/document swaps, worker/request/download settlement, traffic containment, and provider journeys remain uncovered. Audit1363: src/renderer/src/components/browser-pane/browser-client-page-renderer-installation.test.ts removed. Missing preload/web-client flags, mount/rekey/retire forwarding and failure-code projection. No equivalent replacement coverage is claimed. Audit1365: focused Linux unit selection passed on source head 8880357cb420c45f1b808ae545a5bc609324624d. This new result has its own exact command; historical results keep their prior scope. Intentional test losses remain recorded in knownGaps. No physical-provider, native input, rendered E2E, p95, soak or replacement-coverage claim.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4150/refactor-remote-browser-to-client-hosted-electron-webviews" ], "invariant": "A prepared route page binds its opaque authority to one exact main-observed renderer WebContents while that page generation is active or retiring. Before requesting a blank guest, the production command executor must retain the exact execution-host route, verify its key, and prepare the route/profile partition for one still-current renderer generation. Main sends the approved opaque partition and exact page generation, but no target URL, through one bounded request admitted against the exact current renderer object and document generation; only a schema-valid reply from that same object, request, operation, and page generation can settle it. Preload accepts requests only in the top frame, binds outcomes to the admitted request, fails overflow and unavailable subscribers within a bounded interval, and fences callbacks replaced by a newer document subscriber. Renderer retains each blank webview under one non-React document host keyed by the exact partition, page ID, and generation, never reparents it, and holds an attached or process-lost generation until exact destruction. Renderer replacement, WebContents-ID reuse, abort, timeout, malformed reply, disposal, and process loss fence pending work without admitting a late reply. Renderer-document replacement retires before commit, while blocked external navigation is ignored and failed or cancelled provisional navigation restores only the exact surviving frame. A WebContents whose Electron Session has belonged to a prepared route partition is quarantined synchronously after generic guest policy installation, including when page authority disappears between will-attach and did-attach. It must be a live blank webview owned by the exact renderer WebContents. Nonblank navigation remains denied until main matches the exact partition, browser page, page-host generation, guest WebContents, renderer WebContents, and opaque live page authority, then issues a separate grant. Every later navigation rechecks the same opaque guest incarnation and page authority, so reusing a logical tuple or WebContents ID cannot revive a stale guest. Releasing that authority, losing or destroying the guest process, or losing its owning renderer before, during, or after registration synchronously fences pending authority admission, ends exact logical authority, revokes navigation, and closes any attached guest through the same retirement barrier. Failed, aborted, or retired creation attempts revoke the exact guest and renderer mount before releasing the Session and route, attempt every safe cleanup, and never clear or admit a replacement generation after uncertain cleanup. Session and route release require exact guest destruction proof; an ambiguous mount outcome retains them. If close is delayed or fails, the partition stays outside attachment admission and route policies remain installed until the exact destroyed acknowledgement. Route popups remain denied throughout. Active and retiring page maps and pending renderer requests are bounded, stale callbacks cannot retire or clear replacements, and non-route browser guests retain existing behavior.", - "oracle": "Prepare a page for one renderer and require authority lookup and registration by a sibling renderer to fail; reject owner replacement while the generation is active or retiring, then lose the owning renderer before guest registration and require only its prepared pages to retire. Pause partition setup, lose the owner, and require its waiter to fail without authority; add a live sibling waiter to the same pending setup and require only that waiter to admit; exceed the configured waiter cap and require immediate refusal. Make policy cleanup throw in the first of two owned partitions and require the sweep to retire both without restoring admission. Through the production executor, retain one exact route, prepare its partition, mount blank on one current renderer, register and grant the exact guest in order, then load only its normalized HTTP(S) URL. Queue renderer requests before subscription, replace one subscriber, overflow both request and page budgets, race attachment with retirement, delay guest identity until DOM readiness, lose the guest renderer, and require exact bounded settlement without reparenting or cross-partition collision. Under real Electron, require the main bridge to accept only the actual main-frame reply, match the positive renderer WebContents ID to did-attach-webview, destroy it on retirement, and reject and remove a denied unprepared guest. Reject a mismatched route, stale renderer or page generation, and file URL without touching Chromium. Abort or fail registration after mount and require exact guest, renderer, Session, and route cleanup in that order; make renderer cleanup reject but require destruction before later release, and keep the generation fenced from replacement. Make guest retirement fail or mount outcome ambiguous and require every safe cleanup while Session and route remain retained. Destroy a guest spontaneously before command cleanup, reuse its WebContents identity, and require the old opaque claim not to retire the replacement while the replacement claim still can. Attach a blank route guest and require nonblank navigation plus every popup to be denied. Reject a wrong renderer, wrong page generation, nonblank initial document, wrong WebContents type, destroyed guest, and excess attachment; delay or fail its close and require navigation and popups to remain denied. Register the exact prepared tuple and prove navigation remains denied until a second grant; then allow repeated HTTP(S) navigation while continuing to deny file navigation and popups. Release logical page authority with delayed guest close; require immediate navigation revocation, one exact close, no partition admission, no policy cleanup, and same-tuple preparation refusal until destroyed acknowledgement. Make destroyed inspection throw and require retirement plus navigation to remain fail-closed until the explicit destroyed event. Acknowledge destruction, require one policy cleanup, reprepare the tuple, replay stale acknowledgement, and prove the replacement remains admitted. Make retirement startup throw and require policy plus capacity to remain fail-closed. Retire two pages sharing one partition and require cleanup only after both exact acknowledgements. Emit guest render-process-gone and destroyed, and emit owning-renderer process loss through the main-window boundary; require exact logical retirement, close, and grant revocation while unrelated renderer guests and prepared pages survive. Reject retirement for the wrong opaque authority. Reprepare after ordinary release, require a new opaque authority, deny the stale guest, and admit an exact replacement. Destroy a registered guest under real destroyed state, verify best-effort listener release, replay stale cleanup, and prove its replacement remains grantable. Mutate caller input after registration and prove main-owned authority is unchanged. Attach a normal browser Session and require no route-registry mutation.", + "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): Prepare a page for one renderer and require authority lookup and registration by a sibling renderer to fail; reject owner replacement while the generation is active or retiring, then lose the owning renderer before guest registration and require only its prepared pages to retire. Pause partition setup, lose the owner, and require its waiter to fail without authority; add a live sibling waiter to the same pending setup and require only that waiter to admit; exceed the configured waiter cap and require immediate refusal. Make policy cleanup throw in the first of two owned partitions and require the sweep to retire both without restoring admission. Through the production executor, retain one exact route, prepare its partition, mount blank on one current renderer, register and grant the exact guest in order, then load only its normalized HTTP(S) URL. Queue renderer requests before subscription, replace one subscriber, overflow both request and page budgets, race attachment with retirement, delay guest identity until DOM readiness, lose the guest renderer, and require exact bounded settlement without reparenting or cross-partition collision. Under real Electron, require the main bridge to accept only the actual main-frame reply, match the positive renderer WebContents ID to did-attach-webview, destroy it on retirement, and reject and remove a denied unprepared guest. Reject a mismatched route, stale renderer or page generation, and file URL without touching Chromium. Abort or fail registration after mount and require exact guest, renderer, Session, and route cleanup in that order; make renderer cleanup reject but require destruction before later release, and keep the generation fenced from replacement. Make guest retirement fail or mount outcome ambiguous and require every safe cleanup while Session and route remain retained. Destroy a guest spontaneously before command cleanup, reuse its WebContents identity, and require the old opaque claim not to retire the replacement while the replacement claim still can. Attach a blank route guest and require nonblank navigation plus every popup to be denied. Reject a wrong renderer, wrong page generation, nonblank initial document, wrong WebContents type, destroyed guest, and excess attachment; delay or fail its close and require navigation and popups to remain denied. Register the exact prepared tuple and prove navigation remains denied until a second grant; then allow repeated HTTP(S) navigation while continuing to deny file navigation and popups. Release logical page authority with delayed guest close; require immediate navigation revocation, one exact close, no partition admission, no policy cleanup, and same-tuple preparation refusal until destroyed acknowledgement. Make destroyed inspection throw and require retirement plus navigation to remain fail-closed until the explicit destroyed event. Acknowledge destruction, require one policy cleanup, reprepare the tuple, replay stale acknowledgement, and prove the replacement remains admitted. Make retirement startup throw and require policy plus capacity to remain fail-closed. Retire two pages sharing one partition and require cleanup only after both exact acknowledgements. Emit guest render-process-gone and destroyed, and emit owning-renderer process loss through the main-window boundary; require exact logical retirement, close, and grant revocation while unrelated renderer guests and prepared pages survive. Reject retirement for the wrong opaque authority. Reprepare after ordinary release, require a new opaque authority, deny the stale guest, and admit an exact replacement. Destroy a registered guest under real destroyed state, verify best-effort listener release, replay stale cleanup, and prove its replacement remains grantable. Mutate caller input after registration and prove main-owned authority is unchanged. Attach a normal browser Session and require no route-registry mutation.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts src/main/browser/client-pages/renderer/browser-client-page-renderer-bridge.test.ts src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts src/main/browser/routing/sessions/browser-route-session-registry.test.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/preload/browser-client-page-renderer-requests.test.ts src/renderer/src/components/browser-pane/browser-client-page-retained-registry.test.ts src/renderer/src/components/browser-pane/browser-client-page-renderer-installation.test.ts src/main/window/createMainWindow.test.ts src/main/window/renderer-document-navigation.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts src/main/browser/client-pages/renderer/browser-client-page-renderer-bridge.test.ts src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts src/main/browser/routing/sessions/browser-route-session-registry.test.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/preload/browser-client-page-renderer-requests.test.ts src/renderer/src/components/browser-pane/browser-client-page-retained-registry.test.ts src/main/window/createMainWindow.test.ts src/main/window/renderer-document-navigation.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts src/main/browser/client-pages/renderer/browser-client-page-renderer-bridge.test.ts src/main/browser/routing/sessions/browser-route-session-registry.test.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/main/window/createMainWindow.test.ts src/main/window/renderer-document-navigation.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts src/main/browser/routing/sessions/browser-route-prepared-page-rekey.test.ts" ], @@ -7510,7 +7527,6 @@ "src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts", "src/preload/browser-client-page-renderer-requests.test.ts", "src/renderer/src/components/browser-pane/browser-client-page-retained-registry.test.ts", - "src/renderer/src/components/browser-pane/browser-client-page-renderer-installation.test.ts", "src/main/window/createMainWindow.test.ts", "src/main/window/renderer-document-navigation.test.ts" ], @@ -7620,16 +7636,6 @@ } ], "evidenceRuns": [ - { - "date": "2026-08-15", - "runner": "local", - "platform": "macos", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/browser-client-page-command-executor.test.ts src/main/browser/browser-client-page-command-integration.test.ts src/main/browser/browser-client-page-renderer-bridge.test.ts src/main/browser/browser-client-page-renderer-lifecycle.electron.test.ts src/main/browser/browser-client-page-renderer-runtime.test.ts src/main/browser/browser-route-session-registry.test.ts src/main/browser/browser-route-webcontents-registry.test.ts src/preload/browser-client-page-renderer-requests.test.ts src/renderer/src/components/browser-pane/browser-client-page-retained-registry.test.ts src/renderer/src/components/browser-pane/browser-client-page-renderer-installation.test.ts src/main/window/createMainWindow.test.ts src/main/window/renderer-document-navigation.test.ts", - "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts src/main/browser/client-pages/renderer/browser-client-page-renderer-bridge.test.ts src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts src/main/browser/routing/sessions/browser-route-session-registry.test.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/preload/browser-client-page-renderer-requests.test.ts src/renderer/src/components/browser-pane/browser-client-page-retained-registry.test.ts src/renderer/src/components/browser-pane/browser-client-page-renderer-installation.test.ts src/main/window/createMainWindow.test.ts src/main/window/renderer-document-navigation.test.ts", - "result": "passed", - "durationSeconds": 1.22, - "summary": "On the candidate atop #14753, twelve files passed 132 exact opaque-claim navigation revocation, in-flight create fencing, revocation-error cleanup, retained guest destruction separation, route Session, renderer bridge/registry, Electron lifecycle, and main-window document assertions." - }, { "date": "2026-08-14", "runner": "local", @@ -7641,31 +7647,31 @@ "summary": "Eight files and 174 tests passed deterministic route retention, trusted-renderer create ordering, exact renderer WebContents and main-frame-document fencing, subframe and stale-frame rejection, wrong-page and wrong-operation rejection, timeout/send/collision settlement, renderer-document replacement retirement, blocked external and same-document preservation, failed provisional restoration, stale same-URL failure rejection during a live replacement, concurrent failure plus blocked replacement convergence, production IPC wiring, composed real Session/WebContents registry lifecycle, abort and cleanup fencing, Session-index and prepared-owner fencing, bounded pending waiters, late/rejected route-WebContents quarantine, opaque-authority and process-loss fencing, fail-closed shared-partition release barriers, exact registration and navigation, popup denial, and main-window ordering tests." }, { - "date": "2026-08-14", + "date": "2026-11-04", "runner": "local", - "platform": "macos", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/browser-client-page-command-executor.test.ts src/main/browser/browser-client-page-command-integration.test.ts src/main/browser/browser-client-page-renderer-bridge.test.ts src/main/browser/browser-client-page-renderer-lifecycle.electron.test.ts src/main/browser/browser-client-page-renderer-runtime.test.ts src/main/browser/browser-route-session-registry.test.ts src/main/browser/browser-route-webcontents-registry.test.ts src/preload/browser-client-page-renderer-requests.test.ts src/renderer/src/components/browser-pane/browser-client-page-retained-registry.test.ts src/renderer/src/components/browser-pane/browser-client-page-renderer-installation.test.ts src/main/window/createMainWindow.test.ts src/main/window/renderer-document-navigation.test.ts", - "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts src/main/browser/client-pages/renderer/browser-client-page-renderer-bridge.test.ts src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts src/main/browser/routing/sessions/browser-route-session-registry.test.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/preload/browser-client-page-renderer-requests.test.ts src/renderer/src/components/browser-pane/browser-client-page-retained-registry.test.ts src/renderer/src/components/browser-pane/browser-client-page-renderer-installation.test.ts src/main/window/createMainWindow.test.ts src/main/window/renderer-document-navigation.test.ts", + "platform": "linux", + "command": "pnpm --config.verifyDepsBeforeRun=false exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts src/main/browser/client-pages/renderer/browser-client-page-renderer-bridge.test.ts src/main/browser/routing/sessions/browser-route-session-registry.test.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/main/window/createMainWindow.test.ts src/main/window/renderer-document-navigation.test.ts --maxWorkers=2", "result": "passed", - "durationSeconds": 2.7, - "summary": "Twelve files and 199 tests passed the existing main authority gate plus top-frame preload queueing, bounded outcomes, exact retained renderer tuples, delayed guest-ID readiness, idempotent retirement, resource budgets, process-loss fencing, and real Electron main-frame reply, blank attachment, denial, and destruction lifecycle." + "durationSeconds": 5.51, + "summary": "Test Files 7 passed (7); Tests 116 passed (116). Source head 8880357cb420c45f1b808ae545a5bc609324624d. Headless main-only unchanged-source command. No renderer installation replacement or actual WebContents/provider execution claim. Node24.22.0 with ORCA_BACKGROUND_LAUNCH=1 and an isolated Xvfb display.", + "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts src/main/browser/client-pages/renderer/browser-client-page-renderer-bridge.test.ts src/main/browser/routing/sessions/browser-route-session-registry.test.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/main/window/createMainWindow.test.ts src/main/window/renderer-document-navigation.test.ts" } ], "runtimeBudget": { "p95Seconds": 15, - "scope": "deterministic route Session and WebContents authority plus one isolated real-Electron renderer lifecycle" + "scope": "Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." }, "flakeHistory": { "status": "unknown", - "evidence": "The deterministic and isolated real-Electron suite passes locally; CI and cross-platform soak history have not started." + "evidence": "Changed selectors have no new soak result after Audit1363; any retained unchanged-source receipts apply only to their own commands. Historical account: The deterministic and isolated real-Electron suite passes locally; CI and cross-platform soak history have not started." }, "redGreenEvidence": { - "status": "partial", - "evidence": "The route-WebContents oracle first failed because no registry existed, and the Session oracle failed because no exact Session/page index existed. A first candidate blocked every navigation after the initial document committed because it incorrectly required the current URL to remain blank; repeated-navigation evidence failed until blank validation was limited to registration and grant. Mutable-input evidence then proved caller-owned data could alter stored authority until the registry copied it. Fresh review found late and rejected attachments could keep generic navigation policy, destroyed cleanup skipped listener release, and tuple reuse revived stale grants; the added deterministic cases fail that candidate and pass with retained Session recognition, deny-first admission, best-effort destroyed cleanup, and opaque authority tokens. The page-release oracle then failed because no exact retirement handshake existed; it passes with synchronous revocation plus policy cleanup held behind the exact destroyed callback. Guest-process, guest-destruction, and owning-renderer loss tests then failed because none ended logical page authority; the candidate routes all three through exact fenced retirement. Prepared-owner tests subsequently failed because a sibling renderer received the same live authority and no pre-registration renderer-retirement method existed; the candidate binds live authority to the exact owner and sweeps only that renderer's prepared pages. Fresh review then reproduced cleanup-failure sweep abort, pending authority resurrection, and live-partition success after owner loss; snapshot-first retirement, best-effort cleanup, renderer epochs, and the final async-boundary check now fence stale work while allowing an unrelated live waiter to admit the verified partition. The executor baseline lacked the module, exact guest navigation, and unregistered retirement. Later deterministic probes caught early route release after renderer failure, ambiguous mount leakage, failed-create readmission, discarded destruction proof, proof-ledger eviction, WebContents ID reuse, and stale navigation; the candidate keeps a bounded failed-page fence and retains an immutable opaque guest claim whose destruction promise, retirement, and navigation survive spontaneous loss without targeting a replacement. Renderer-lifecycle review then reproduced blocked-navigation detachment, stale same-URL cancellation, and a concurrent failure plus blocked-replacement stuck fence; constant document-generation and idle-state tracking makes those exact sequences green without retaining a navigation list. The renderer baseline had no preload consumer or retained page registry. Its first real-Electron candidate failed because getWebContentsId was transiently unavailable at did-attach, then because pre-attach destruction released state without rejecting the mount; DOM-readiness retry and exact pre-attach destruction settlement make both sequences green. A later deterministic sequence proved did-attach cancelled the timeout before a guest ID existed and retirement released the observed guest without destruction; retaining the deadline through valid identity and recording observed attachment make both sequences green. Fresh review then caught cached re-advertisement after guest identity became unreadable and an unhandled rejection when reply transport threw; exact live-ID comparison now fences the stale incarnation, while safe reply construction and transport containment leave main's timeout as the bounded recovery. Real Electron mutation/revert, lifetime page-generation authority, worker/request settlement, and traffic evidence remain required before activation." + "status": "missing", + "evidence": "Audit1363 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The route-WebContents oracle first failed because no registry existed, and the Session oracle failed because no exact Session/page index existed. A first candidate blocked every navigation after the initial document committed because it incorrectly required the current URL to remain blank; repeated-navigation evidence failed until blank validation was limited to registration and grant. Mutable-input evidence then proved caller-owned data could alter stored authority until the registry copied it. Fresh review found late and rejected attachments could keep generic navigation policy, destroyed cleanup skipped listener release, and tuple reuse revived stale grants; the added deterministic cases fail that candidate and pass with retained Session recognition, deny-first admission, best-effort destroyed cleanup, and opaque authority tokens. The page-release oracle then failed because no exact retirement handshake existed; it passes with synchronous revocation plus policy cleanup held behind the exact destroyed callback. Guest-process, guest-destruction, and owning-renderer loss tests then failed because none ended logical page authority; the candidate routes all three through exact fenced retirement. Prepared-owner tests subsequently failed because a sibling renderer received the same live authority and no pre-registration renderer-retirement method existed; the candidate binds live authority to the exact owner and sweeps only that renderer's prepared pages. Fresh review then reproduced cleanup-failure sweep abort, pending authority resurrection, and live-partition success after owner loss; snapshot-first retirement, best-effort cleanup, renderer epochs, and the final async-boundary check now fence stale work while allowing an unrelated live waiter to admit the verified partition. The executor baseline lacked the module, exact guest navigation, and unregistered retirement. Later deterministic probes caught early route release after renderer failure, ambiguous mount leakage, failed-create readmission, discarded destruction proof, proof-ledger eviction, WebContents ID reuse, and stale navigation; the candidate keeps a bounded failed-page fence and retains an immutable opaque guest claim whose destruction promise, retirement, and navigation survive spontaneous loss without targeting a replacement. Renderer-lifecycle review then reproduced blocked-navigation detachment, stale same-URL cancellation, and a concurrent failure plus blocked-replacement stuck fence; constant document-generation and idle-state tracking makes those exact sequences green without retaining a navigation list. The renderer baseline had no preload consumer or retained page registry. Its first real-Electron candidate failed because getWebContentsId was transiently unavailable at did-attach, then because pre-attach destruction released state without rejecting the mount; DOM-readiness retry and exact pre-attach destruction settlement make both sequences green. A later deterministic sequence proved did-attach cancelled the timeout before a guest ID existed and retirement released the observed guest without destruction; retaining the deadline through valid identity and recording observed attachment make both sequences green. Fresh review then caught cached re-advertisement after guest identity became unreadable and an unhandled rejection when reply transport threw; exact live-ID comparison now fences the stale incarnation, while safe reply construction and transport containment leave main's timeout as the bounded recovery. Real Electron mutation/revert, lifetime page-generation authority, worker/request settlement, and traffic evidence remain required before activation." }, "performanceBudget": { "required": true, - "evidence": "Session, guest, page, and exact-owner lookups are O(1), install no polling, and retain at most 256 attached route guests in registry maps in addition to the lower 64-partition and 64-active-or-retiring-page-per-partition bounds. The production executor retains at most 256 active, creating, or failed page IDs; each observed guest owns one immutable lifecycle claim and one destruction promise, with no global tombstone ledger. The renderer bridge retains at most 512 pending mount or retirement requests, one timer and optional abort listener per request, and one app-lifetime IPC reply listener; settlement, abort, timeout, replacement, and disposal remove each exactly once. Preload independently retains at most 512 validated requests and one timer each, removes queued identifiers on every settlement, and exposes one replaceable subscriber. The renderer retains at most 256 exact page tuples and 64 per partition, one host, webview, timer, promise, and four lifecycle listeners each; attached retirement keeps bounded fail-closed tombstones until destruction. Renderer-document tracking retains only constant generation, active-fence, and cancellation state across concurrent navigation events. At most 64 callers per partition can await one setup promise. Renderer loss scans at most 256 guests plus 4,096 bounded active pages and snapshots only exact owner matches. Each guest retains at most one retirement callback. Historical Session recognition uses weak keys. Normal guests perform one bounded Session lookup at did-attach. Destroyed guests synchronously release exact mappings and attempt each listener removal independently." + "evidence": "Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Session, guest, page, and exact-owner lookups are O(1), install no polling, and retain at most 256 attached route guests in registry maps in addition to the lower 64-partition and 64-active-or-retiring-page-per-partition bounds. The production executor retains at most 256 active, creating, or failed page IDs; each observed guest owns one immutable lifecycle claim and one destruction promise, with no global tombstone ledger. The renderer bridge retains at most 512 pending mount or retirement requests, one timer and optional abort listener per request, and one app-lifetime IPC reply listener; settlement, abort, timeout, replacement, and disposal remove each exactly once. Preload independently retains at most 512 validated requests and one timer each, removes queued identifiers on every settlement, and exposes one replaceable subscriber. The renderer retains at most 256 exact page tuples and 64 per partition, one host, webview, timer, promise, and four lifecycle listeners each; attached retirement keeps bounded fail-closed tombstones until destruction. Renderer-document tracking retains only constant generation, active-fence, and cancellation state across concurrent navigation events. At most 64 callers per partition can await one setup promise. Renderer loss scans at most 256 guests plus 4,096 bounded active pages and snapshots only exact owner matches. Each guest retains at most one retirement callback. Historical Session recognition uses weak keys. Normal guests perform one bounded Session lookup at did-attach. Destroyed guests synchronously release exact mappings and attempt each listener removal independently." }, "promotionCriteria": [ "Use Playwright CDP in real Electron to prove did-attach lockdown precedes page script, popup, redirect, worker, and speculative activity.", @@ -7681,7 +7687,11 @@ "A failed or ambiguous create remains fenced until authenticated inventory reconciliation proves whether the guest exists; a real transport-loss recovery journey remains to be recorded.", "The runtime-owned placement registry supplies monotonic page generations after retirement; persistence across a full authority restart remains deterministic rather than a packaged-upgrade journey.", "Popup reservations do not exist; every route guest popup is denied.", - "The production caller derives renderer, page, host generation, and route identity from live main-owned state; physical Windows and Linux Electron ordering remain unvalidated." + "The production caller derives renderer, page, host generation, and route identity from live main-owned state; physical Windows and Linux Electron ordering remain unvalidated.", + "Audit1363: src/renderer/src/components/browser-pane/browser-client-page-renderer-installation.test.ts removed. Missing preload/web-client flags, mount/rekey/retire forwarding and failure-code projection. No equivalent replacement coverage is claimed.", + "Audit1363 retires this complete dated receipt because a source in its selector was deleted or reduced. It does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-08-15\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/browser-client-page-command-executor.test.ts src/main/browser/browser-client-page-command-integration.test.ts src/main/browser/browser-client-page-renderer-bridge.test.ts src/main/browser/browser-client-page-renderer-lifecycle.electron.test.ts src/main/browser/browser-client-page-renderer-runtime.test.ts src/main/browser/browser-route-session-registry.test.ts src/main/browser/browser-route-webcontents-registry.test.ts src/preload/browser-client-page-renderer-requests.test.ts src/renderer/src/components/browser-pane/browser-client-page-retained-registry.test.ts src/renderer/src/components/browser-pane/browser-client-page-renderer-installation.test.ts src/main/window/createMainWindow.test.ts src/main/window/renderer-document-navigation.test.ts\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts src/main/browser/client-pages/renderer/browser-client-page-renderer-bridge.test.ts src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts src/main/browser/routing/sessions/browser-route-session-registry.test.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/preload/browser-client-page-renderer-requests.test.ts src/renderer/src/components/browser-pane/browser-client-page-retained-registry.test.ts src/renderer/src/components/browser-pane/browser-client-page-renderer-installation.test.ts src/main/window/createMainWindow.test.ts src/main/window/renderer-document-navigation.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 1.22,\n \"summary\": \"On the candidate atop #14753, twelve files passed 132 exact opaque-claim navigation revocation, in-flight create fencing, revocation-error cleanup, retained guest destruction separation, route Session, renderer bridge/registry, Electron lifecycle, and main-window document assertions.\"\n }", + "Audit1363 retires this complete dated receipt because a source in its selector was deleted or reduced. It does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-08-14\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/browser-client-page-command-executor.test.ts src/main/browser/browser-client-page-command-integration.test.ts src/main/browser/browser-client-page-renderer-bridge.test.ts src/main/browser/browser-client-page-renderer-lifecycle.electron.test.ts src/main/browser/browser-client-page-renderer-runtime.test.ts src/main/browser/browser-route-session-registry.test.ts src/main/browser/browser-route-webcontents-registry.test.ts src/preload/browser-client-page-renderer-requests.test.ts src/renderer/src/components/browser-pane/browser-client-page-retained-registry.test.ts src/renderer/src/components/browser-pane/browser-client-page-renderer-installation.test.ts src/main/window/createMainWindow.test.ts src/main/window/renderer-document-navigation.test.ts\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts src/main/browser/client-pages/execution/browser-client-page-command-integration.test.ts src/main/browser/client-pages/renderer/browser-client-page-renderer-bridge.test.ts src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts src/main/browser/routing/sessions/browser-route-session-registry.test.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/preload/browser-client-page-renderer-requests.test.ts src/renderer/src/components/browser-pane/browser-client-page-retained-registry.test.ts src/renderer/src/components/browser-pane/browser-client-page-renderer-installation.test.ts src/main/window/createMainWindow.test.ts src/main/window/renderer-document-navigation.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 2.7,\n \"summary\": \"Twelve files and 199 tests passed the existing main authority gate plus top-frame preload queueing, bounded outcomes, exact retained renderer tuples, delayed guest-ID readiness, idempotent retirement, resource budgets, process-loss fencing, and real Electron main-frame reply, blank attachment, denial, and destruction lifecycle.\"\n }", + "Audit1363 historical platform/provider scope before source changes: {\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[]}. Remaining provider scope applies only to unchanged-source receipts." ], "demotionRule": "Demote if a route guest can navigate nonblank before exact registration and grant, a mismatched, released, crashed, or ownerless page remains authoritative, tuple reuse revives stale authority, page release clears route policy before exact guest destruction, a stale retirement clears a replacement, a popup reaches shell.openExternal or an unregistered native window, a rejected attachment retains navigation or popup capability, stale cleanup retires a replacement, normal browser guests change behavior, or any claimed exact identity is sourced only from renderer input." }, @@ -13499,7 +13509,7 @@ "providers": ["local", "daemon", "ssh", "remote-runtime"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": [], - "coverageNotes": "Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1320 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser native-keyboard fallback inventory case. Its empty-chord, absent-layout and no-op-subscription alarms are lost; retained native input evidence is not an equivalent replacement. Historical commands and results remain historical. Local macOS and containerized Linux evidence, deterministic renderer-unit coverage for the Linux/Sogou candidate-key policy including the legacy orphaned-keyup fallback, xterm preedit visibility and row-occlusion behavior, Electron/CDP preedit geometry, Electron/CDP live-PTY Sogou-style repros, and macOS renderer/main slices for Preview kitty commits and layout-native Option input. The Option slice covers complete CSI-u flag fields including lock state, repeat/release event types, authoritative committed associated text, native dead-key release suppression, functional-versus-printable numpad codes, press-pinned release identity, live keyup modifiers, pending-layout text fallback, atomic layout refresh, rapid in-focus input-source changes, stable native layout characters, and both native/web preload fallbacks. The standalone remote SnapshotStart metadata suite is removed. Its proven-zero, nonzero, absent-field and malformed-value propagation alarms are intentionally lost; retained daemon and preview consumer contracts do not establish equivalent remote projection coverage. Historical commands and results remain historical. Real Linux/Sogou OS IME automation, native Windows candidate-window placement, Windows ConPTY post-agent reset, and the CJK/Vietnamese/Arabic matrix remain registered gaps. The audit removes isolated candidate-anchor width, last-column, timer-ordering and detached-textarea examples. The retained deterministic fixtures do not observe a native candidate window or establish equivalent geometry coverage; separate Electron geometry evidence remains historical. The test-value audit removes the empty end-of-row/no-tail composition baseline from terminal-korean-midline-preedit-occlusion.spec.ts. The placeholder masking and measured row-tail occlusion registrations remain; they are not equivalent replacement coverage for the removed empty-tail alarm. No new execution or native IME evidence is claimed. Audit1301: src/renderer/src/components/terminal-pane/terminal-shortcut-option-compose.test.ts reduced. Dead-key/IME variants, Unicode/language inventories, numpad/CapsLock cases and other protocol samples lose their individual alarms. No equivalent replacement coverage is claimed. Audit1320: src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts reduced. Last-complete snapshot while layout-map/native-snapshot partial refresh settles loses its individual implementation-cache alarm. No equivalent replacement coverage is claimed. Audit1342: src/renderer/src/components/terminal-pane/terminal-ime-macos-keybinding-dict-trace.test.ts reduced. Second Korean-layout replay, ordinary Korean/ASCII no-remap baselines and weak Option nonempty-byte alarm are dropped. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit1361 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1320 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser native-keyboard fallback inventory case. Its empty-chord, absent-layout and no-op-subscription alarms are lost; retained native input evidence is not an equivalent replacement. Historical commands and results remain historical. Local macOS and containerized Linux evidence, deterministic renderer-unit coverage for the Linux/Sogou candidate-key policy including the legacy orphaned-keyup fallback, xterm preedit visibility and row-occlusion behavior, Electron/CDP preedit geometry, Electron/CDP live-PTY Sogou-style repros, and macOS renderer/main slices for Preview kitty commits and layout-native Option input. The Option slice covers complete CSI-u flag fields including lock state, repeat/release event types, authoritative committed associated text, native dead-key release suppression, functional-versus-printable numpad codes, press-pinned release identity, live keyup modifiers, pending-layout text fallback, atomic layout refresh, rapid in-focus input-source changes, stable native layout characters, and both native/web preload fallbacks. The standalone remote SnapshotStart metadata suite is removed. Its proven-zero, nonzero, absent-field and malformed-value propagation alarms are intentionally lost; retained daemon and preview consumer contracts do not establish equivalent remote projection coverage. Historical commands and results remain historical. Real Linux/Sogou OS IME automation, native Windows candidate-window placement, Windows ConPTY post-agent reset, and the CJK/Vietnamese/Arabic matrix remain registered gaps. The audit removes isolated candidate-anchor width, last-column, timer-ordering and detached-textarea examples. The retained deterministic fixtures do not observe a native candidate window or establish equivalent geometry coverage; separate Electron geometry evidence remains historical. The test-value audit removes the empty end-of-row/no-tail composition baseline from terminal-korean-midline-preedit-occlusion.spec.ts. The placeholder masking and measured row-tail occlusion registrations remain; they are not equivalent replacement coverage for the removed empty-tail alarm. No new execution or native IME evidence is claimed. Audit1301: src/renderer/src/components/terminal-pane/terminal-shortcut-option-compose.test.ts reduced. Dead-key/IME variants, Unicode/language inventories, numpad/CapsLock cases and other protocol samples lose their individual alarms. No equivalent replacement coverage is claimed. Audit1320: src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts reduced. Last-complete snapshot while layout-map/native-snapshot partial refresh settles loses its individual implementation-cache alarm. No equivalent replacement coverage is claimed. Audit1342: src/renderer/src/components/terminal-pane/terminal-ime-macos-keybinding-dict-trace.test.ts reduced. Second Korean-layout replay, ordinary Korean/ASCII no-remap baselines and weak Option nonempty-byte alarm are dropped. No equivalent replacement coverage is claimed. Audit1361: src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts removed. Snapshot/live-proven kitty flags, replacement choice and replay idempotence in the assembled mirror. No equivalent replacement coverage is claimed. Audit1365: focused Linux unit selection passed on source head 8880357cb420c45f1b808ae545a5bc609324624d. This new result has its own exact command; historical results keep their prior scope. Intentional test losses remain recorded in knownGaps. No physical-provider, native input, rendered E2E, p95, soak or replacement-coverage claim.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/6699", "https://github.com/stablyai/orca/pull/6682", @@ -13510,12 +13520,12 @@ "https://github.com/stablyai/orca/pull/17170" ], "invariant": "Composition, native text forwarding, synthetic input, paste, and platform keyboard bypass paths must not send preedit/control bytes before commit and must commit text exactly once to the intended PTY. A live preedit must stay visible across an IME-resumed transaction, preserve every committed row-tail cell hidden by its opaque overlay, mask only a structurally verified Codex or Claude placeholder and never a row carrying typed text, keep the themed insertion caret and native candidate anchor inside the terminal at the final column, and clean up without stale overlay children or ownership classes. Layout-native Option text must preserve negotiated CSI-u alternate/associated fields and lock modifiers, distinguish repeat from press, and resolve releases with the press's primary identity plus the actual keyup modifiers without exposing a partial or stale layout refresh. An in-focus macOS input-source change must invalidate both renderer authorities before the next key can use the old source. When the snapshot source proves kitty state, macOS Preview commits must use the application's effective flags after the sequenced snapshot and every proven replay/live transition, and a claimed press delivered under report_event_types must produce exactly one matching release regardless of whether keyup arrives before or after insertText and regardless of xterm's defensive internal reset.", - "oracle": "The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Exact outbound bytes from the REAL native-text forwarder behind installPreviewImeBridge after initial snapshot restore, replacement resync, live transitions, and both keydown->insertText->keyup and keydown->keyup->insertText orderings; a wiring-only mock is supporting evidence, not the oracle. The current renderer-unit slice asserts native text commits route to the intended PTY once, composition/preedit bookkeeping does not leak premature text, resumed Windows event traces reactivate the visible preedit, an opaque mid-line overlay reproduces the committed row tail it covers, arbitrary DIM output remains visible, and final-column layout keeps both caret and textarea candidate anchor within the available screen width. The retained candidate-anchor slice checks layout-read caching, deferred timer coalescing, recognized-screen follow-ups and refit refresh with deterministic DOM fixtures. A Codex frame whose prompt row is bold and whose dimmed model footer sits below a blank gap acquires the mask class while composing; the same placeholder text without that footer, a framed-versus-unframed Claude prompt, a row of arbitrary dimmed output, and a row carrying typed text do not. The class is gone after composition end, after a blur that is not followed by a session end, and after disposal. Rendered Electron/CDP geometry independently proves the overlay reproduces every committed cell it hides, that a real Codex placeholder at column 2 is masked rather than repeated, and that the final-column caret, preedit, and textarea right edges all land inside the screen. Input-source classification handles synthetic/native paths, paste/runtime forwarding avoids duplicate terminal payloads for covered fixtures, and real fcitx4/Sogou captures send only the committed candidate for Space/digit picks while ordinary typing, literal Space and digits stay available. A main/preload/renderer notification chain proves every live window invalidates immediately, the old native read settles before a coalesced refresh signal, and older refreshes are generation-fenced. The Electron/CDP live-PTY repro verifies Sogou-style Space and digit selectors submit only the committed Chinese text. Real legacy IME commit preservation, native candidate-window placement, and the full CJK/Vietnamese/Arabic/JIS-yen matrix run in follow-up platform soak where automation is possible.", + "oracle": "The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Exact outbound bytes from the REAL native-text forwarder behind installPreviewImeBridge after initial snapshot restore, replacement resync, live transitions, and both keydown->insertText->keyup and keydown->keyup->insertText orderings; a wiring-only mock is supporting evidence, not the oracle. The current renderer-unit slice asserts native text commits route to the intended PTY once, composition/preedit bookkeeping does not leak premature text, resumed Windows event traces reactivate the visible preedit, an opaque mid-line overlay reproduces the committed row tail it covers, arbitrary DIM output remains visible, and final-column layout keeps both caret and textarea candidate anchor within the available screen width. The retained candidate-anchor slice checks layout-read caching, deferred timer coalescing, recognized-screen follow-ups and refit refresh with deterministic DOM fixtures. A Codex frame whose prompt row is bold and whose dimmed model footer sits below a blank gap acquires the mask class while composing; the same placeholder text without that footer, a framed-versus-unframed Claude prompt, a row of arbitrary dimmed output, and a row carrying typed text do not. The class is gone after composition end, after a blur that is not followed by a session end, and after disposal. Rendered Electron/CDP geometry independently proves the overlay reproduces every committed cell it hides, that a real Codex placeholder at column 2 is masked rather than repeated, and that the final-column caret, preedit, and textarea right edges all land inside the screen. Input-source classification handles synthetic/native paths, paste/runtime forwarding avoids duplicate terminal payloads for covered fixtures, and real fcitx4/Sogou captures send only the committed candidate for Space/digit picks while ordinary typing, literal Space and digits stay available. A main/preload/renderer notification chain proves every live window invalidates immediately, the old native read settles before a coalesced refresh signal, and older refreshes are generation-fenced. The Electron/CDP live-PTY repro verifies Sogou-style Space and digit selectors submit only the committed Chinese text. Real legacy IME commit preservation, native candidate-window placement, and the full CJK/Vietnamese/Arabic/JIS-yen matrix run in follow-up platform soak where automation is possible.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/terminal-ime-substituted-text-commit.test.ts src/renderer/src/components/terminal-pane/terminal-ime-macos-keybinding-dict-trace.test.ts src/renderer/src/components/terminal-pane/terminal-paste-runtime.test.ts src/renderer/src/components/terminal-pane/terminal-ime-composition-tracker.test.ts src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts src/renderer/src/components/terminal-pane/xterm-bypass-policy-non-mac.test.ts src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-ime-linux-fcitx4-trace-replay.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-ime-xterm-midline-preedit-tail.test.ts src/renderer/src/components/terminal-pane/terminal-ime-xterm-resumed-preedit-visibility.test.ts src/renderer/src/components/terminal-pane/terminal-ime-xterm-trailing-preedit-occlusion.test.ts src/renderer/src/lib/pane-manager/terminal-ime-candidate-anchor.test.ts src/renderer/src/components/terminal-pane/terminal-ime-composer-placeholder-mask.test.ts src/shared/terminal/input/terminal-composer-draft.test.ts src/main/daemon/terminal-cursor-line-context.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx src/renderer/src/components/dashboard-popout/AgentTerminalPreview.option-dead-key.test.tsx src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/main/daemon/daemon-pty-adapter.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx src/renderer/src/components/dashboard-popout/AgentTerminalPreview.option-dead-key.test.tsx src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/main/daemon/daemon-pty-adapter.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-kitty-csi-u-encoding.test.ts src/renderer/src/components/terminal-pane/terminal-shortcut-option-compose.test.ts src/renderer/src/components/terminal-pane/terminal-option-kitty-release.test.ts src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts src/renderer/src/lib/keyboard-layout/option-as-alt-probe.test.ts src/main/ipc/macos-keyboard-layout-snapshot.test.ts src/main/ipc/macos-keyboard-layout-change-notifications.test.ts src/preload/app-restart-checkpoint-routing.test.ts src/renderer/src/web/web-preload-api-ui.test.ts", "pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts", "pnpm run test:e2e -- tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts", @@ -13549,7 +13559,6 @@ "src/preload/app-restart-checkpoint-routing.test.ts", "src/renderer/src/web/web-preload-api-ui.test.ts", "src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts", - "src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts", "src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx", "src/renderer/src/components/dashboard-popout/AgentTerminalPreview.option-dead-key.test.tsx", "src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts", @@ -13728,16 +13737,6 @@ "auto-repeat, two-key rollover, a swallowed commit, a retired claim, blur, and disposal each emit at most one release and never synthesize one" ] }, - { - "file": "src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts", - "assertions": [ - "a Preview opened on a snapshot carrying flags 8 adopts 8 before any live output", - "a replacement snapshot whose ANSI carries no kitty bytes keeps its proven flags, and a proven 0 clears an earlier 8", - "a missing field leaves the mirror unproven at the raw-text fallback and a later live negotiation still upgrades it", - "restored flags land on the screen the snapshot scan selected", - "a proven post-snapshot suffix advances the stack while redelivered bytes apply idempotently" - ] - }, { "file": "src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx", "assertions": [ @@ -13817,16 +13816,6 @@ "durationSeconds": 13.9, "summary": "The Electron live-PTY IME gate passed three scenarios covering Windows IME Shift commit, candidate-selector suppression with committed Chinese text, and composed text/cursor/Backspace stability; the opt-in real-agent scenario remained skipped." }, - { - "date": "2026-08-16", - "runner": "local", - "platform": "macos", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx src/renderer/src/components/dashboard-popout/AgentTerminalPreview.option-dead-key.test.tsx src/shared/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/renderer/src/runtime/remote-runtime-terminal-snapshot-kitty-flags.test.ts src/main/daemon/daemon-pty-adapter.test.ts", - "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx src/renderer/src/components/dashboard-popout/AgentTerminalPreview.option-dead-key.test.tsx src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/main/daemon/daemon-pty-adapter.test.ts", - "result": "passed", - "durationSeconds": 4.3, - "summary": "9 test files and 172 tests passed, covering the Preview kitty slice: real forwarder bytes at snapshot-proven flags, press/release pairing across both keyup/insertText orderings, native and configured-side dead-key release ownership, and flag provenance where a proven 0, a proven non-zero, and an absent field stay three distinct facts — asserted on the daemon snapshot and on a host-pushed remote snapshot that carries the flags with their sequence. The emitter-side rule that a remote SnapshotStart withholds flags without a seq has no direct assertion yet; the client-side gate is what these files pin." - }, { "date": "2026-10-13", "runner": "local", @@ -13853,6 +13842,16 @@ "result": "passed", "durationSeconds": 72, "summary": "Electron/CDP IME repro passed: Sogou candidate selection, post-composition candidate selection, and existing Chinese IME harness passed; real Codex IME test was skipped behind ORCA_E2E_REAL_CODEX_IME." + }, + { + "date": "2026-11-04", + "runner": "local", + "platform": "linux", + "command": "pnpm --config.verifyDepsBeforeRun=false exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx src/renderer/src/components/dashboard-popout/AgentTerminalPreview.option-dead-key.test.tsx src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/main/daemon/daemon-pty-adapter.test.ts --maxWorkers=2", + "result": "passed", + "durationSeconds": 8.88, + "summary": "Test Files 7 passed (7); Tests 151 passed (151). Source head 8880357cb420c45f1b808ae545a5bc609324624d. Focused current retained command; no live provider/native input/soak/benchmark or removed-case equivalence claim. Node24.22.0 with ORCA_BACKGROUND_LAUNCH=1 and an isolated Xvfb display.", + "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx src/renderer/src/components/dashboard-popout/AgentTerminalPreview.option-dead-key.test.tsx src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/main/daemon/daemon-pty-adapter.test.ts" } ], "runtimeBudget": { @@ -13861,15 +13860,15 @@ }, "flakeHistory": { "status": "unknown", - "evidence": "Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1320; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1301; any retained unchanged-source receipts apply only to their own commands. Historical account: Focused renderer input tests and the Electron/CDP Sogou-style repro are now registered; needs soak history and true platform IME evidence before promotion." + "evidence": "Changed selectors have no new soak result after Audit1361; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1320; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1301; any retained unchanged-source receipts apply only to their own commands. Historical account: Focused renderer input tests and the Electron/CDP Sogou-style repro are now registered; needs soak history and true platform IME evidence before promotion." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1320 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1301 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Focused tests cover existing native-text, input-source, paste/runtime forwarding, Linux/Sogou candidate selector, post-composition guard contracts, live-PTY Sogou-style candidate commits, and the Preview kitty slice (press/release pairing in both keyup orderings, and snapshot flag provenance separating a proven 0 from an absent field). Needs intentional-break proof for duplicate native text forwarding and composition preedit leakage, plus the broader language/platform matrix." + "evidence": "Audit1361 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1320 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1301 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Focused tests cover existing native-text, input-source, paste/runtime forwarding, Linux/Sogou candidate selector, post-composition guard contracts, live-PTY Sogou-style candidate commits, and the Preview kitty slice (press/release pairing in both keyup orderings, and snapshot flag provenance separating a proven 0 from an absent field). Needs intentional-break proof for duplicate native text forwarding and composition preedit leakage, plus the broader language/platform matrix." }, "performanceBudget": { "required": true, - "evidence": "Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Terminal input hot-path audit clean through 2026-08-29: candidate guards retain O(1) checks and bounded per-pane state. Xterm overlay reconciliation scans only the current row, bounded by terminal columns, retains at most three current DOM children, reuses one preedit-bounds layout read for the visual geometry and the textarea the OS samples, and cancels its single deferred timer on replacement and disposal. The candidate anchor adds no layout read of its own: it clamps from the inline width xterm just wrote. Orca's placeholder binding reads the bounded visible cursor context at composition start and on xterm render only while a session is active, retaining one active session id and one disposable render listener. Layout changes add one process-lifetime native listener, two singleton renderer subscriptions, one O(live windows) broadcast per OS event, and generation-fenced refreshes whose native helper read is deduplicated in flight. The paths are event-driven and add no polling, per-key IPC, SSH/remote transport work, unbounded queues, or retained terminal data." + "evidence": "Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Terminal input hot-path audit clean through 2026-08-29: candidate guards retain O(1) checks and bounded per-pane state. Xterm overlay reconciliation scans only the current row, bounded by terminal columns, retains at most three current DOM children, reuses one preedit-bounds layout read for the visual geometry and the textarea the OS samples, and cancels its single deferred timer on replacement and disposal. The candidate anchor adds no layout read of its own: it clamps from the inline width xterm just wrote. Orca's placeholder binding reads the bounded visible cursor context at composition start and on xterm render only while a session is active, retaining one active session id and one disposable render listener. Layout changes add one process-lifetime native listener, two singleton renderer subscriptions, one O(live windows) broadcast per OS event, and generation-fenced refreshes whose native helper read is deduplicated in flight. The paths are event-driven and add no polling, per-key IPC, SSH/remote transport work, unbounded queues, or retained terminal data." }, "promotionCriteria": [ "Cover deterministic byte/cell oracles first.", @@ -13893,7 +13892,11 @@ "Audit1342 retires this complete dated receipt because a source in its selector was deleted or reduced. It does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-08-09\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/terminal-ime-substituted-text-commit.test.ts src/renderer/src/components/terminal-pane/terminal-ime-macos-keybinding-dict-trace.test.ts src/renderer/src/components/terminal-pane/terminal-paste-runtime.test.ts src/renderer/src/components/terminal-pane/terminal-ime-composition-tracker.test.ts src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts src/renderer/src/components/terminal-pane/xterm-bypass-policy-non-mac.test.ts src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 0.7,\n \"summary\": \"8 test file(s) passed, 143 tests, after adding the OS key-binding substitution replay. Discrimination checked by mutation rather than assumed: suppressing the structural claim, and separately removing the single character the older punctuation table happened to list, each make the replay send the raw layout character while both paired negatives stay green.\"\n }", "Audit1342 retires this complete dated receipt because a source in its selector was deleted or reduced. It does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-07-07\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/terminal-ime-substituted-text-commit.test.ts src/renderer/src/components/terminal-pane/terminal-ime-macos-keybinding-dict-trace.test.ts src/renderer/src/components/terminal-pane/terminal-paste-runtime.test.ts src/renderer/src/components/terminal-pane/terminal-ime-composition-tracker.test.ts src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts src/renderer/src/components/terminal-pane/xterm-bypass-policy-non-mac.test.ts src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 0.7,\n \"summary\": \"7 test file(s) passed, 144 tests passed on the Linux/Sogou candidate-key branch (includes held-key repeat guard coverage). The command shown is the gate's current one, which the manifest check requires; the run itself predates two of the files it now lists. The 2026-08-09 entry is the one that covers the current slice.\"\n }", "Audit1342 historical platform/provider scope before source changes: {\"coveredPlatforms\":[\"macos\",\"linux\"],\"coveredProviders\":[]}. Remaining provider scope applies only to unchanged-source receipts.", - "Audit1342 historical assertion inventory for deleted/reduced sources; not current validated assertions:\n[\n {\n \"file\": \"src/renderer/src/components/terminal-pane/terminal-ime-macos-keybinding-dict-trace.test.ts\",\n \"assertions\": [\n \"an OS key-binding substitution reaches the PTY instead of the raw layout character\",\n \"the same key with no substitution in play still sends the layout character\"\n ]\n }\n]" + "Audit1342 historical assertion inventory for deleted/reduced sources; not current validated assertions:\n[\n {\n \"file\": \"src/renderer/src/components/terminal-pane/terminal-ime-macos-keybinding-dict-trace.test.ts\",\n \"assertions\": [\n \"an OS key-binding substitution reaches the PTY instead of the raw layout character\",\n \"the same key with no substitution in play still sends the layout character\"\n ]\n }\n]", + "Audit1361: src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts removed. Snapshot/live-proven kitty flags, replacement choice and replay idempotence in the assembled mirror. No equivalent replacement coverage is claimed.", + "Audit1361 retires this complete dated receipt because a source in its selector was deleted or reduced. It does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-08-16\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx src/renderer/src/components/dashboard-popout/AgentTerminalPreview.option-dead-key.test.tsx src/shared/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/renderer/src/runtime/remote-runtime-terminal-snapshot-kitty-flags.test.ts src/main/daemon/daemon-pty-adapter.test.ts\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx src/renderer/src/components/dashboard-popout/AgentTerminalPreview.option-dead-key.test.tsx src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/main/daemon/daemon-pty-adapter.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 4.3,\n \"summary\": \"9 test files and 172 tests passed, covering the Preview kitty slice: real forwarder bytes at snapshot-proven flags, press/release pairing across both keyup/insertText orderings, native and configured-side dead-key release ownership, and flag provenance where a proven 0, a proven non-zero, and an absent field stay three distinct facts — asserted on the daemon snapshot and on a host-pushed remote snapshot that carries the flags with their sequence. The emitter-side rule that a remote SnapshotStart withholds flags without a seq has no direct assertion yet; the client-side gate is what these files pin.\"\n }", + "Audit1361 historical platform/provider scope before source changes: {\"coveredPlatforms\":[\"macos\",\"linux\"],\"coveredProviders\":[]}. Remaining provider scope applies only to unchanged-source receipts.", + "Audit1361 historical assertion inventory for deleted/reduced sources; not current validated assertions:\n[\n {\n \"file\": \"src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts\",\n \"assertions\": [\n \"a Preview opened on a snapshot carrying flags 8 adopts 8 before any live output\",\n \"a replacement snapshot whose ANSI carries no kitty bytes keeps its proven flags, and a proven 0 clears an earlier 8\",\n \"a missing field leaves the mirror unproven at the raw-text fallback and a later live negotiation still upgrades it\",\n \"restored flags land on the screen the snapshot scan selected\",\n \"a proven post-snapshot suffix advances the stack while redelivered bytes apply idempotently\"\n ]\n }\n]" ], "demotionRule": "Cannot promote if success is based only on DOM text without PTY byte/cell evidence." }, diff --git a/config/renderer-layout-writer-baseline.txt b/config/renderer-layout-writer-baseline.txt index cf5e4ba3224..7a2bd27ab6a 100644 --- a/config/renderer-layout-writer-baseline.txt +++ b/config/renderer-layout-writer-baseline.txt @@ -9,8 +9,6 @@ 1 src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.ts 1 src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-statuses.ts 4 src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-send-target-inputs.ts -3 src/renderer/src/components/sidebar/worktree-list/listing/worktree-list-lineage-store-state.ts -3 src/renderer/src/components/sidebar/worktree-list/listing/worktree-list-pinned-store-state.ts 4 src/renderer/src/components/sidebar/worktree-list/listing/use-agent-send-target.ts 1 src/renderer/src/components/status-bar/workspace-space-decision-inputs.ts 2 src/renderer/src/components/tab-bar/terminal-tab-activity-status.ts diff --git a/config/scripts/ci-shard-timings.json b/config/scripts/ci-shard-timings.json index 3af4992a99f..40a5c26621c 100644 --- a/config/scripts/ci-shard-timings.json +++ b/config/scripts/ci-shard-timings.json @@ -990,7 +990,6 @@ "src/main/ai-vault-search/session-search-scope-service.test.ts": 191, "src/main/ai-vault-search/session-search-service-registry.test.ts": 193, "src/main/ai-vault-search/session-search-service.test.ts": 379, - "src/main/ai-vault-search/session-search-sidebar-parity.test.ts": 361, "src/main/ai-vault-search/session-search-snippet-marks.test.ts": 230, "src/main/ai-vault-search/session-search-sqlite-support.test.ts": 49, "src/main/ai-vault-search/session-search-store-is-memory.test.ts": 805, @@ -1749,7 +1748,6 @@ "src/main/codex-accounts/runtime-home-legacy-migration.test.ts": 1147, "src/main/codex-accounts/runtime-home-managed-auth-recovery.test.ts": 658, "src/main/codex-accounts/runtime-home-mirror-login-copy.test.ts": 1012, - "src/main/codex-accounts/runtime-home-mirrored-status-home.test.ts": 575, "src/main/codex-accounts/runtime-home-per-account-homes.test.ts": 1107, "src/main/codex-accounts/runtime-home-rate-limit-pinned-distro.test.ts": 521, "src/main/codex-accounts/runtime-home-read-only-launch-resolution.test.ts": 978, @@ -1952,7 +1950,6 @@ "src/main/codex/structured/journal/codex-turn-ordinals.test.ts": 86, "src/main/codex/structured/catalog/codex-usage-limits.test.ts": 312, "src/main/codex/trust/hooks/codex-user-hook-trust-moves.test.ts": 125, - "src/main/codex/configuration/homes/codex-windows-sandbox-read-grant.test.ts": 84, "src/main/codex/hooks/installation/codex-wsl-hook-install-plan.test.ts": 890, "src/main/codex/configuration/settings/config-features-settings-promotion.test.ts": 179, "src/main/codex/configuration/settings/config-plugin-registration-promotion.test.ts": 306, @@ -3107,7 +3104,6 @@ "src/main/ipc/runtime-environments/runtime-environment-status-connection.test.ts": 1270, "src/main/ipc/runtime-environments/runtime-environment-status-retirement.test.ts": 575, "src/main/ipc/runtime-environments/runtime-environment-subscription-identity.test.ts": 1786, - "src/main/ipc/runtime-environments/runtime-environment-subscription-layout-recording.test.ts": 1265, "src/main/ipc/runtime-environments/runtime-environment-support-routing.test.ts": 1063, "src/main/ipc/runtime-environments/runtime-environment-transport-generation.test.ts": 41, "src/main/ipc/runtime-environments/runtime-environments-call-routing.test.ts": 4342, @@ -4915,7 +4911,6 @@ "src/main/runtime/dsh-launch-prompt-resubmit.test.ts": 6527, "src/main/runtime/dsh-readiness-transcript.test.ts": 71, "src/main/runtime/e2ee-keypair.test.ts": 77, - "src/main/runtime/editor-open-active-group.test.ts": 4298, "src/main/runtime/editor-view-layout-apply.test.ts": 6870, "src/main/runtime/editor-view-partition-changes.test.ts": 5531, "src/main/runtime/editor-view-switch-off.test.ts": 1879, @@ -5076,7 +5071,6 @@ "src/main/runtime/orca-runtime-mobile-markdown-tab-routes.test.ts": 8386, "src/main/runtime/orca-runtime-on-pty-data-redraw.test.ts": 4613, "src/main/runtime/orca-runtime-process-incarnation-liveness.test.ts": 4768, - "src/main/runtime/orca-runtime-provider-reattach-launch-identity.test.ts": 4061, "src/main/runtime/orca-runtime-quick-open-capabilities.test.ts": 547, "src/main/runtime/orca-runtime-read-kitty-file.test.ts": 4304, "src/main/runtime/orca-runtime-serve-browser-restore.test.ts": 4469, @@ -5473,7 +5467,6 @@ "src/main/runtime/rpc/methods/orchestration/worker/worker-stop-exit-race.test.ts": 4508, "src/main/runtime/rpc/methods/orchestration/worker/worker-stop-liveness-verdict.test.ts": 5279, "src/main/runtime/rpc/methods/orchestration/worker/worker-terminal-custody-at-creation.test.ts": 5687, - "src/main/runtime/rpc/methods/orchestration/worker/worker-worktree-creation.test.ts": 54, "src/main/runtime/rpc/methods/orchestration/worker/workers-new-worktree.test.ts": 6117, "src/main/runtime/rpc/methods/orchestration/worker/workers-recovery.test.ts": 5182, "src/main/runtime/rpc/methods/paired-caller-host-id.test.ts": 54, @@ -6278,7 +6271,6 @@ "src/main/ssh/orcad-terminal-census-client.test.ts": 217, "src/main/ssh/orcad-tunneled-pairing.test.ts": 94, "src/main/ssh/orcad-unreachable-setup-release.test.ts": 2336, - "src/main/ssh/orcad-unreachable-setup-stop.test.ts": 332, "src/main/ssh/orcad-update-admission-fence.test.ts": 397, "src/main/ssh/orcad-update-plan.test.ts": 642, "src/main/ssh/pinned-runtime-host-target.test.ts": 45, @@ -6791,7 +6783,6 @@ "src/preload/usage-provider-api.test.ts": 46, "src/renderer/src/app-shell/app-command-handlers-child-workspaces.test.ts": 1576, "src/renderer/src/app-shell/app-command-handlers-tab-rename.test.ts": 1786, - "src/renderer/src/app-shell/app-command-handlers-workspace-delete.test.ts": 748, "src/renderer/src/app-shell/app-root-surface-settings.test.tsx": 480, "src/renderer/src/app-shell/app-window-chrome.test.ts": 47, "src/renderer/src/app-shell/headless-phone-window-parity.test.ts": 1904, @@ -6839,7 +6830,6 @@ "src/renderer/src/components/NativeChatResumeOnRestartModal.test.tsx": 3511, "src/renderer/src/components/NewWorkspaceComposerCard.file-drop.test.tsx": 871, "src/renderer/src/components/NewWorkspaceComposerCard.quick-file-drop.test.tsx": 4557, - "src/renderer/src/components/NewWorkspaceComposerCard.set-location-warm.test.tsx": 1187, "src/renderer/src/components/NewWorkspaceComposerCard.set-location.test.tsx": 1301, "src/renderer/src/components/NewWorkspaceComposerCard.start-from.test.tsx": 1385, "src/renderer/src/components/NewWorkspaceComposerCard.test.tsx": 2246, @@ -7039,7 +7029,6 @@ "src/renderer/src/components/browser-pane/assemble-chrome/browser-egress-indicator.test.tsx": 2115, "src/renderer/src/components/browser-pane/assemble-chrome/browser-link-status-bubble.test.tsx": 1818, "src/renderer/src/components/browser-pane/assemble-chrome/browser-navigation-control-row.test.tsx": 427, - "src/renderer/src/components/browser-pane/assemble-chrome/browser-page-extension-menu-items.test.tsx": 279, "src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.adoption-chrome.test.tsx": 25933, "src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.retention-props.test.tsx": 3808, "src/renderer/src/components/browser-pane/assemble-chrome/ssh-routed-browser-page-gate.test.tsx": 5288, @@ -7051,7 +7040,6 @@ "src/renderer/src/components/browser-pane/browser-client-page-metadata-publisher.test.ts": 315, "src/renderer/src/components/browser-pane/browser-client-page-position-driver.test.ts": 509, "src/renderer/src/components/browser-pane/browser-client-page-profile-staging.test.ts": 434, - "src/renderer/src/components/browser-pane/browser-client-page-renderer-installation.test.ts": 451, "src/renderer/src/components/browser-pane/browser-client-page-retained-drag-passthrough.test.ts": 501, "src/renderer/src/components/browser-pane/browser-client-page-retained-registry.test.ts": 550, "src/renderer/src/components/browser-pane/browser-external-app-prompt.test.ts": 204, @@ -7155,25 +7143,21 @@ "src/renderer/src/components/dashboard-popout/preview-grid-claim.test.ts": 436, "src/renderer/src/components/dashboard-popout/preview-terminal-box-fit-lifecycle.test.ts": 192, "src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts": 479, - "src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts": 57, "src/renderer/src/components/dashboard-popout/remote-runtime-terminal-preview-api.test.ts": 81, "src/renderer/src/components/dashboard-popout/use-agent-dashboard-telemetry.test.ts": 2108, "src/renderer/src/components/dashboard-popout/useDashboardSnapshot.test.tsx": 432, "src/renderer/src/components/dashboard/AgentDashboardDrawer.focus.test.tsx": 2567, "src/renderer/src/components/dashboard/AgentDashboardDrawer.test.tsx": 1981, - "src/renderer/src/components/dashboard/DashboardAgentChildDisclosure.test.tsx": 2490, "src/renderer/src/components/dashboard/DashboardAgentRow.test.tsx": 2350, "src/renderer/src/components/dashboard/agent-dashboard-open-mode.test.ts": 48, "src/renderer/src/components/dashboard/agent-destination-navigation.integration.test.tsx": 3232, "src/renderer/src/components/dashboard/agent-row-lineage-model.test.ts": 107, - "src/renderer/src/components/dashboard/agent-row-pane-live-title.test.ts": 48, "src/renderer/src/components/dashboard/build-dashboard-bucket-counts.allocation.test.ts": 1072, "src/renderer/src/components/dashboard/build-dashboard-bucket-counts.equivalence.test.ts": 722, "src/renderer/src/components/dashboard/build-dashboard-snapshot-folder-workspace.test.ts": 2150, "src/renderer/src/components/dashboard/build-dashboard-snapshot.rows-cache.test.ts": 3640, "src/renderer/src/components/dashboard/build-dashboard-snapshot.test.ts": 2121, "src/renderer/src/components/dashboard/dashboard-card-terminal-input.test.ts": 1879, - "src/renderer/src/components/dashboard/dashboard-worktree-launch-options.test.ts": 535, "src/renderer/src/components/dashboard/reveal-dashboard-agent.test.ts": 1098, "src/renderer/src/components/dashboard/use-agent-row-conversation-name.test.ts": 88, "src/renderer/src/components/dashboard/useAgentBucketCounts.test.tsx": 318, @@ -7251,12 +7235,10 @@ "src/renderer/src/components/editor/model-lifetime/retention/closed-editor-view-state-retention.test.ts": 9012, "src/renderer/src/components/editor/closed-unsaved-files-toast.test.ts": 448, "src/renderer/src/components/editor/combined-diff/scroll-viewport/combined-diff-cursor-reveal.test.tsx": 3685, - "src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree-collapsed-work.test.tsx": 823, "src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree-render.test.tsx": 923, "src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree-windowing.test.tsx": 854, "src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree.test.ts": 259, "src/renderer/src/components/editor/combined-diff/browse-files/use-combined-diff-file-tree-resize.test.tsx": 308, - "src/renderer/src/components/editor/combined-diff/browse-files/use-combined-diff-tree-navigation.test.ts": 324, "src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-load-scheduler.test.ts": 53, "src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-metadata-retention.test.tsx": 1151, "src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-section-connection.test.ts": 1699, @@ -7291,16 +7273,11 @@ "src/renderer/src/components/editor/view-mode/custom-editor-routing.test.ts": 2715, "src/renderer/src/components/editor/rich-markdown/details/details-markdown-html.test.ts": 93, "src/renderer/src/components/editor/diff/monaco-view/diff-editor-shift-wheel-scroll.test.ts": 194, - "src/renderer/src/components/editor/diff/monaco-view/diff-editor-word-wrap-options.test.ts": 184, - "src/renderer/src/components/editor/diff/monaco-view/diff-model-swap-view-state.test.ts": 183, - "src/renderer/src/components/editor/diff/monaco-view/diff-monaco-model-disposal.test.ts": 55, - "src/renderer/src/components/editor/diff/review/diff-navigation-context.test.tsx": 1968, "src/renderer/src/components/editor/diff/sections/diff-section-layout.test.ts": 95, "src/renderer/src/components/editor/save/flush/discard-editor-file-changes.save-race.test.ts": 1150, "src/renderer/src/components/editor/rich-markdown/schema/drag-selection-guard-lifetime.test.ts": 626, "src/renderer/src/components/editor/autosave/editor-autosave-conflict-flow.test.ts": 1931, "src/renderer/src/components/editor/autosave/editor-autosave-controller.test.ts": 2324, - "src/renderer/src/components/editor/autosave/editor-autosave-holds.test.ts": 960, "src/renderer/src/components/editor/autosave/editor-autosave.test.ts": 529, "src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-adapter.test.ts": 2812, "src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-entry-points.parity.test.ts": 1804, @@ -7316,8 +7293,6 @@ "src/renderer/src/components/editor/editor-header.test.ts": 208, "src/renderer/src/components/editor/model-lifetime/identity/editor-model-host-isolation.test.ts": 5906, "src/renderer/src/components/editor/model-lifetime/identity/editor-model-uri-labels.test.ts": 1223, - "src/renderer/src/components/editor/model-lifetime/identity/editor-model-uri-language-service.test.ts": 3283, - "src/renderer/src/components/editor/model-lifetime/identity/editor-model-uri.test.ts": 81, "src/renderer/src/components/editor/editor-panel-draft-selector.test.ts": 558, "src/renderer/src/components/editor/editor-panel-render-model.test.ts": 2795, "src/renderer/src/components/editor/editor-path-display.test.ts": 45, @@ -7339,7 +7314,6 @@ "src/renderer/src/components/editor/save/queue/editor-save-shared-model.test.ts": 1239, "src/renderer/src/components/editor/external-changes/editor-self-write-registry.test.ts": 63, "src/renderer/src/components/editor/model-lifetime/buffer-text/editor-shared-record-clean-view.test.ts": 1998, - "src/renderer/src/components/editor/editor-untitled-dont-save-dialogs.test.tsx": 1216, "src/renderer/src/components/editor/save/commands/editor-untitled-save-lifecycle.test.ts": 1485, "src/renderer/src/components/editor/image-png-export.chromium.test.ts": 212, "src/renderer/src/components/editor/image-png-export.test.ts": 50, @@ -7357,12 +7331,10 @@ "src/renderer/src/components/editor/markdown/documents/markdown-document-list-request.test.ts": 495, "src/renderer/src/components/editor/markdown-export-extract.test.ts": 214, "src/renderer/src/components/editor/markdown-export-html.test.ts": 47, - "src/renderer/src/components/editor/markdown/link-routing/markdown-internal-links.test.ts": 53, "src/renderer/src/components/editor/markdown/navigation/markdown-navigation-details.test.ts": 626, "src/renderer/src/components/editor/markdown-preview/document-worker/markdown-preview-document-client.test.ts": 65, "src/renderer/src/components/editor/markdown-preview/document-worker/markdown-preview-document-search-budget.test.ts": 400, "src/renderer/src/components/editor/markdown-preview/document-worker/markdown-preview-document-search-cache.test.ts": 588, - "src/renderer/src/components/editor/markdown-preview/document-worker/markdown-preview-document-search-scope.test.ts": 442, "src/renderer/src/components/editor/markdown-preview/document-worker/markdown-preview-document.test.ts": 1670, "src/renderer/src/components/editor/markdown/link-routing/markdown-preview-links.test.ts": 74, "src/renderer/src/components/editor/markdown-preview/links/markdown-preview-local-images.test.ts": 1639, @@ -7377,7 +7349,6 @@ "src/renderer/src/components/editor/markdown/render-mode/markdown-rich-mode.test.ts": 5289, "src/renderer/src/components/editor/markdown/render-mode/markdown-round-trip.test.ts": 2334, "src/renderer/src/components/editor/markdown/source-scanning/markdown-scanner-boundaries.test.ts": 96, - "src/renderer/src/components/editor/markdown/navigation/markdown-table-of-contents.test.ts": 146, "src/renderer/src/components/editor/mermaid-config.test.ts": 581, "src/renderer/src/components/editor/mermaid-sanitize.chromium.test.ts": 313, "src/renderer/src/components/editor/monaco-auto-height.test.ts": 98, @@ -7403,25 +7374,20 @@ "src/renderer/src/components/editor/rich-markdown/raw-source/raw-markdown-html-line-break.test.ts": 2188, "src/renderer/src/components/editor/rich-markdown/raw-source/raw-markdown-html.details-fences.test.ts": 84, "src/renderer/src/components/editor/save/flush/removal-unsaved-editor-files.records.test.ts": 1738, - "src/renderer/src/components/editor/save/flush/removal-unsaved-editor-files.test.ts": 700, "src/renderer/src/components/editor/restored-editor-owner-save-lifecycle.test.ts": 2482, "src/renderer/src/components/editor/restored-editor-same-workspace-reown.test.tsx": 2409, "src/renderer/src/components/editor/restored-editor-workspace-runtime-owner.test.tsx": 2464, "src/renderer/src/components/editor/rich-markdown/review/rich-markdown-annotation-highlight.mapping.test.ts": 368, "src/renderer/src/components/editor/rich-markdown/images/rich-markdown-async-image-paste.test.ts": 1524, "src/renderer/src/components/editor/rich-markdown/images/rich-markdown-async-image-table.test.ts": 1402, - "src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-auto-focus.test.ts": 172, "src/renderer/src/components/editor/rich-markdown/images/rich-markdown-blob-image-paste.test.ts": 2127, - "src/renderer/src/components/editor/rich-markdown/lists/rich-markdown-blockquote-list.test.ts": 2229, "src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-clipboard-links.test.ts": 2434, "src/renderer/src/components/editor/rich-markdown/code-blocks/rich-markdown-code-block-indent.test.ts": 1981, - "src/renderer/src/components/editor/rich-markdown/doc-links/rich-markdown-commands.test.ts": 2312, "src/renderer/src/components/editor/rich-markdown/review/rich-markdown-comment-blocks.test.ts": 1959, "src/renderer/src/components/editor/rich-markdown/commands/rich-markdown-context-command-routing.test.ts": 2157, "src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-cut.test.ts": 371, "src/renderer/src/components/editor/rich-markdown/details/rich-markdown-details-keyboard.test.ts": 7747, "src/renderer/src/components/editor/rich-markdown/doc-links/rich-markdown-doc-link-keyboard.test.ts": 336, - "src/renderer/src/components/editor/rich-markdown/doc-links/rich-markdown-doc-link-resolution.test.ts": 265, "src/renderer/src/components/editor/rich-markdown/links/rich-markdown-editor-click-routing.test.ts": 1002, "src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-editor-config.test.ts": 2794, "src/renderer/src/components/editor/rich-markdown/schema/rich-markdown-empty-paragraph-delete.test.ts": 224, @@ -7431,7 +7397,6 @@ "src/renderer/src/components/editor/rich-markdown/links/rich-markdown-file-uri-links.test.ts": 2472, "src/renderer/src/components/editor/rich-markdown/citations/rich-markdown-html-superscript-link.test.ts": 3769, "src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-attributes.test.ts": 2412, - "src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-capacity.test.ts": 2506, "src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-context.test.ts": 676, "src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-cut.test.ts": 2685, "src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert-code-block.test.ts": 1078, @@ -7445,7 +7410,6 @@ "src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-large-text-paste.test.ts": 404, "src/renderer/src/components/editor/rich-markdown/lists/rich-markdown-list-continuation.test.ts": 201, "src/renderer/src/components/editor/rich-markdown/lists/rich-markdown-list-outdent.test.ts": 2695, - "src/renderer/src/components/editor/rich-markdown/document/rich-markdown-literal-serialization.test.ts": 205, "src/renderer/src/components/editor/rich-markdown/images/rich-markdown-local-image.test.ts": 2627, "src/renderer/src/components/editor/rich-markdown/code-blocks/rich-markdown-lowlight-ownership.test.ts": 312, "src/renderer/src/components/editor/rich-markdown/code-blocks/rich-markdown-lowlight.test.ts": 2369, @@ -7479,7 +7443,6 @@ "src/renderer/src/components/editor/model-lifetime/buffer-text/use-editor-content-change-handler.undo-clean.test.tsx": 1299, "src/renderer/src/components/editor/use-editor-group-file-drop-owner.remote.test.tsx": 4163, "src/renderer/src/components/editor/use-editor-group-file-drop-owner.test.tsx": 2691, - "src/renderer/src/components/editor/markdown/documents/use-markdown-document-watch-refresh.test.ts": 641, "src/renderer/src/components/editor/markdown-preview/search/use-markdown-preview-document-search.test.tsx": 274, "src/renderer/src/components/editor/markdown-preview/document-worker/use-markdown-preview-document.test.tsx": 326, "src/renderer/src/components/editor/markdown-preview/viewport/use-markdown-preview-navigation.test.tsx": 524, @@ -7495,7 +7458,6 @@ "src/renderer/src/components/editor/rich-markdown/tables/use-rich-markdown-table-control-target.test.tsx": 2094, "src/renderer/src/components/editor/diff/large-files/useDiffViewerLargeDiffLifecycle.test.tsx": 272, "src/renderer/src/components/editor/save/commands/useEditorCmdSaveRequest.test.tsx": 732, - "src/renderer/src/components/editor/useEditorPanelActiveTabContentLoad.overview.test.tsx": 2064, "src/renderer/src/components/editor/useEditorPanelContentState.test.tsx": 3214, "src/renderer/src/components/editor/external-changes/useEditorPanelExternalContentEvents.test.tsx": 2018, "src/renderer/src/components/editor/useEditorPanelFileLoadRetry.host-connection.test.tsx": 2075, @@ -7598,7 +7560,6 @@ "src/renderer/src/components/jira-project-picker.test.tsx": 689, "src/renderer/src/components/jira-prompt-templates.test.ts": 197, "src/renderer/src/components/landing-preflight-runtime-boundary.test.ts": 1915, - "src/renderer/src/components/landing-preflight-unverifiable-host.test.tsx": 2026, "src/renderer/src/components/linear-issue-attribute-filter-dropdowns.test.tsx": 1717, "src/renderer/src/components/linear-issue-attribute-filter-primary-team.test.ts": 48, "src/renderer/src/components/linear-issue-attribute-filter-team-ids.test.ts": 63, @@ -8014,7 +7975,6 @@ "src/renderer/src/components/pr-check-counts.test.ts": 193, "src/renderer/src/components/pull-request-page/actions/merge-actions.test.ts": 383, "src/renderer/src/components/pull-request-page/cache/file-content.test.ts": 344, - "src/renderer/src/components/pull-request-page/files/combined-diff-section-index.test.tsx": 872, "src/renderer/src/components/pull-request-page/mentions/options.test.ts": 179, "src/renderer/src/components/pull-request-page/mentions/query.test.ts": 47, "src/renderer/src/components/pull-request-page/page/use-details.test.tsx": 745, @@ -8160,7 +8120,6 @@ "src/renderer/src/components/plugins/frames/plugin-frame-host-declarative.test.ts": 439, "src/renderer/src/components/plugins/frames/plugin-frame-host.test.ts": 389, "src/renderer/src/components/right-sidebar/plugin-panels/health/plugin-panel-act-driver.test.ts": 293, - "src/renderer/src/components/right-sidebar/plugin-panels/health/plugin-panel-watchdog-visibility.test.ts": 302, "src/renderer/src/components/right-sidebar/plugin-panels/health/plugin-panel-watchdog.test.ts": 116, "src/renderer/src/components/right-sidebar/ports-panel-host.test.ts": 344, "src/renderer/src/components/right-sidebar/checks-panel/comments/pr-comments-ai-launch-ack.test.ts": 118, @@ -8169,7 +8128,6 @@ "src/renderer/src/components/right-sidebar/right-sidebar-titlebar-drag-regions.render.test.tsx": 1044, "src/renderer/src/components/right-sidebar/source-control/ai/runSourceControlAgentActionStart.test.ts": 1917, "src/renderer/src/components/right-sidebar/source-control/ai/source-control-action-recipe-match.test.ts": 316, - "src/renderer/src/components/right-sidebar/source-control/listing/source-control-active-open-file-keys.test.ts": 204, "src/renderer/src/components/right-sidebar/source-control/panel/source-control-branch-context-row.test.tsx": 790, "src/renderer/src/components/right-sidebar/source-control/commit/source-control-commit-message-rows.test.ts": 96, "src/renderer/src/components/right-sidebar/source-control/review/source-control-create-pr-intent-flow.test.ts": 71, @@ -8185,9 +8143,7 @@ "src/renderer/src/components/right-sidebar/source-control/listing/source-control-submodule-expansion.test.ts": 80, "src/renderer/src/components/right-sidebar/source-control/panel/source-control-too-many-changes-banner.test.tsx": 2195, "src/renderer/src/components/right-sidebar/source-control/ai/use-ai.operation-recovery.test.tsx": 13031, - "src/renderer/src/components/right-sidebar/source-control/commit/discard-all-failure-description.test.tsx": 1974, "src/renderer/src/components/right-sidebar/source-control/commit/rename-mutation-paths.test.ts": 49, - "src/renderer/src/components/right-sidebar/source-control/commit/source-control-discard-editor-owner.test.tsx": 878, "src/renderer/src/components/right-sidebar/source-control/commit/source-control-entry-failure-toast.test.ts": 486, "src/renderer/src/components/right-sidebar/source-control/commit/use-bulk-actions-capped-stage.test.tsx": 1991, "src/renderer/src/components/right-sidebar/source-control/commit/use-commit-message-generation.cancel.test.ts": 1992, @@ -8204,7 +8160,6 @@ "src/renderer/src/components/right-sidebar/source-control/sync/git-history-format.test.ts": 266, "src/renderer/src/components/right-sidebar/source-control/sync/use-git-history-wsl-wake.test.tsx": 2095, "src/renderer/src/components/right-sidebar/ssh-port-forward-dialog.ime-enter.test.tsx": 585, - "src/renderer/src/components/right-sidebar/source-control/sync/stale-conflict-operation-poll.test.tsx": 186, "src/renderer/src/components/right-sidebar/ai-vault/scope/use-ai-vault-panel-query.test.tsx": 263, "src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search-focus-request.test.tsx": 1860, "src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search.test.tsx": 688, @@ -8379,7 +8334,6 @@ "src/renderer/src/components/sidebar/project-admission/dialog/AddProjectFromFolderDialog.test.tsx": 271, "src/renderer/src/components/sidebar/host-admission/ssh/AddRemoteHostDialog.config-picker.test.tsx": 1178, "src/renderer/src/components/sidebar/project-admission/dialog/AddRepoDialogChrome.test.tsx": 714, - "src/renderer/src/components/sidebar/project-admission/nested-import/AddRepoNestedImportStep.test.tsx": 635, "src/renderer/src/components/sidebar/project-admission/dialog/AddRepoStartSteps.test.tsx": 822, "src/renderer/src/components/sidebar/host-admission/wsl/AddWslHostFormPanel.test.tsx": 291, "src/renderer/src/components/sidebar/workspace-card/identity/AutoRenameFailedDialog.test.tsx": 2254, @@ -8399,14 +8353,12 @@ "src/renderer/src/components/sidebar/workspace-actions/deletion/DeleteNestedWorktreesDialog.test.tsx": 1807, "src/renderer/src/components/sidebar/workspace-actions/deletion/DeleteWorktreeDialog.test.tsx": 1290, "src/renderer/src/components/sidebar/workspace-actions/deletion/DeleteWorktreeDialog.unsaved-edits.test.tsx": 1150, - "src/renderer/src/components/sidebar/workspace-actions/deletion/DeleteWorktreeDialogFooter.test.tsx": 680, "src/renderer/src/components/sidebar/workspace-actions/deletion/DeleteWorktreeTargetPreview.test.tsx": 2363, "src/renderer/src/components/sidebar/HostRemoveDialog.test.tsx": 6650, "src/renderer/src/components/sidebar/LinearAgentSkillSetupPrompt.reminder-toast.test.tsx": 2248, "src/renderer/src/components/sidebar/LinearAgentSkillSetupPrompt.test.tsx": 2676, "src/renderer/src/components/sidebar/LocalGitToolchainScanBanner.test.tsx": 2025, "src/renderer/src/components/sidebar/MarkdownImageLightbox.test.tsx": 2284, - "src/renderer/src/components/sidebar/worktree-list/listing/NewExternalWorktreesInboxLine.test.tsx": 1953, "src/renderer/src/components/sidebar/project-admission/dialog/NonGitFolderDialog.test.tsx": 2473, "src/renderer/src/components/sidebar/worktree-list/rows/NoticeHostGlyph.test.tsx": 2697, "src/renderer/src/components/sidebar/host-path-browser/RemoteFileBrowser.keyboard.test.tsx": 825, @@ -8450,7 +8402,6 @@ "src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.card-memo-stability.test.tsx": 2053, "src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.folder-workspace-rows.test.ts": 8880, "src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-agent-expansion-coupling.test.tsx": 5388, - "src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-child-card.test.ts": 4388, "src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-child-real-card.test.tsx": 4426, "src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.status-lane-lineage-drop.test.tsx": 3576, "src/renderer/src/components/sidebar/workspace-card/metadata/WorktreeMetaDialog.host-scope.test.tsx": 2215, @@ -8463,13 +8414,11 @@ "src/renderer/src/components/sidebar/project-admission/completion/add-repo-skip-finalization.test.ts": 59, "src/renderer/src/components/sidebar/worktree-list/listing/agent-send-picker-collapse.test.tsx": 2284, "src/renderer/src/components/sidebar/chat-markdown-math-typeset.test.ts": 1336, - "src/renderer/src/components/sidebar/workspace-card/identity/child-workspaces-toggle-visibility.test.ts": 2580, "src/renderer/src/components/sidebar/worktree-list/grouping/default-branch-folder-project-root.test.ts": 227, "src/renderer/src/components/sidebar/worktree-list/grouping/default-branch-visible-under-hide-sleeping.test.ts": 261, "src/renderer/src/components/sidebar/workspace-actions/deletion/delete-worktree-always-force-preference.test.tsx": 2175, "src/renderer/src/components/sidebar/workspace-actions/deletion/delete-worktree-dirty-change-counts.test.ts": 258, "src/renderer/src/components/sidebar/workspace-actions/deletion/delete-worktree-dirty-change-hydration.test.tsx": 910, - "src/renderer/src/components/sidebar/workspace-actions/deletion/delete-worktree-failure-toast.test.tsx": 2072, "src/renderer/src/components/sidebar/workspace-actions/deletion/delete-worktree-flow.test.ts": 1014, "src/renderer/src/components/sidebar/workspace-actions/deletion/delete-worktree-parallel-flow.test.ts": 938, "src/renderer/src/components/sidebar/workspace-actions/deletion/delete-worktree-toast.test.ts": 206, @@ -8479,28 +8428,21 @@ "src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-path-status.test.tsx": 2113, "src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit-host-platform.test.ts": 2264, "src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit.test.ts": 2665, - "src/renderer/src/components/sidebar/workspace-actions/deletion/folder-workspace-delete.test.ts": 788, "src/renderer/src/components/sidebar/worktree-list/listing/hide-sleeping-transient-pty-gap.test.ts": 2211, "src/renderer/src/components/sidebar/worktree-list/drag/host-header-drag.test.tsx": 281, "src/renderer/src/components/sidebar/worktree-list/grouping/host-section-project-headers.test.ts": 308, "src/renderer/src/components/sidebar/worktree-list/grouping/host-section-reveal.test.tsx": 2294, "src/renderer/src/components/sidebar/worktree-list/grouping/host-section-rows.test.ts": 83, "src/renderer/src/components/sidebar/workspace-actions/deletion/hovered-workspace-delete.test.ts": 1640, - "src/renderer/src/components/sidebar/worktree-list/listing/imported-worktrees-card-actions.test.ts": 204, "src/renderer/src/components/sidebar/linear-agent-skill-setup-reminders.test.ts": 52, - "src/renderer/src/components/sidebar/workspace-creation/base-ref-update/local-base-ref-suggestion-toast.test.tsx": 363, "src/renderer/src/components/sidebar/worktree-list/listing/manual-sort-switch-toast.test.ts": 1753, "src/renderer/src/components/sidebar/markdown-top-level-blocks.test.ts": 543, "src/renderer/src/components/sidebar/mobile-sidebar-onboarding-badge.test.ts": 230, - "src/renderer/src/components/sidebar/worktree-list/listing/new-external-worktrees-inbox-actions.test.ts": 211, "src/renderer/src/components/sidebar/worktree-list/grouping/pinned-section-worktrees.test.ts": 446, "src/renderer/src/components/sidebar/workspace-actions/deletion/preserved-branch-batch-toast.test.tsx": 627, - "src/renderer/src/components/sidebar/workspace-actions/deletion/preserved-branch-toast.test.tsx": 628, "src/renderer/src/components/sidebar/project-admission/completion/project-added-default-checkout.test.ts": 128, - "src/renderer/src/components/sidebar/worktree-list/drag/project-group-header-drag-commit.test.ts": 207, "src/renderer/src/components/sidebar/worktree-list/drag/project-group-header-drag-start.test.ts": 205, "src/renderer/src/components/sidebar/worktree-list/drag/project-group-header-drop.test.ts": 198, - "src/renderer/src/components/sidebar/worktree-list/drag/project-header-drag-commit.test.ts": 222, "src/renderer/src/components/sidebar/worktree-list/drag/project-header-drag-start.test.ts": 190, "src/renderer/src/components/sidebar/worktree-list/drag/project-header-drop.test.ts": 206, "src/renderer/src/components/sidebar/project-move-pause-follower.test.ts": 938, @@ -8517,10 +8459,7 @@ "src/renderer/src/components/sidebar/project-admission/host-selection/use-add-repo-windows-drive-refusal.test.tsx": 470, "src/renderer/src/components/sidebar/project-admission/host-selection/use-add-repo-wsl-host-paths.test.tsx": 660, "src/renderer/src/components/sidebar/sidebar-feedback/use-feedback-image-drop.test.tsx": 511, - "src/renderer/src/components/sidebar/sidebar-feedback/use-sidebar-feedback-images.test.tsx": 406, - "src/renderer/src/components/sidebar/workspace-board/surface/use-visible-workspace-kanban-worktree-ids.test.tsx": 1994, "src/renderer/src/components/sidebar/workspace-board/projection/use-workspace-board-task-status-sync.queued.test.ts": 1022, - "src/renderer/src/components/sidebar/workspace-board/drag/use-workspace-kanban-card-pointer-drag.test.ts": 97, "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, @@ -8537,14 +8476,11 @@ "src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-indexes.test.ts": 259, "src/renderer/src/components/sidebar/worktree-list/listing/visible-worktrees.test.ts": 314, "src/renderer/src/components/sidebar/workspace-card/review/workspace-attachment-source-result.test.ts": 1897, - "src/renderer/src/components/sidebar/workspace-board/drag/workspace-board-host-column-drops.test.tsx": 2164, "src/renderer/src/components/sidebar/workspace-board/projection/workspace-board-task-status-sync.test.ts": 378, "src/renderer/src/components/sidebar/workspace-board/drag/workspace-board-twin-drops.test.tsx": 2179, "src/renderer/src/components/sidebar/workspace-actions/deletion/workspace-delete-lineage.test.ts": 51, - "src/renderer/src/components/sidebar/workspace-card/review/workspace-hover-attachments.test.ts": 234, "src/renderer/src/components/sidebar/workspace-board/search/workspace-kanban-search.test.ts": 176, "src/renderer/src/components/sidebar/workspace-board/drag/workspace-kanban-sidebar-drop.test.ts": 1891, - "src/renderer/src/components/sidebar/workspace-board/viewport/workspace-kanban-virtual-lane-layout.test.ts": 64, "src/renderer/src/components/sidebar/workspace-actions/context-menu/workspace-lineage-menu-actions.test.ts": 235, "src/renderer/src/components/sidebar/worktree-list/controls/workspace-options-menu-items.test.tsx": 630, "src/renderer/src/components/sidebar/workspace-card/review/workspace-reference-detail-read.test.ts": 662, @@ -8560,10 +8496,8 @@ "src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.stable-message.test.tsx": 2166, "src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-idle-child-agents.test.ts": 1899, "src/renderer/src/components/sidebar/workspace-card/surface/worktree-card-option-items.test.tsx": 459, - "src/renderer/src/components/sidebar/workspace-card/review/worktree-card-pr-display.test.ts": 197, "src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-status-inputs.test.ts": 55, "src/renderer/src/components/sidebar/workspace-actions/deletion/worktree-delete-host-qualification.test.ts": 1225, - "src/renderer/src/components/sidebar/worktree-list/viewport/worktree-header-section-boundaries.test.ts": 66, "src/renderer/src/components/sidebar/worktree-list/navigation/worktree-keyboard-cycle.test.ts": 131, "src/renderer/src/components/sidebar/worktree-list/drag/worktree-lineage-drag-drop.test.ts": 200, "src/renderer/src/components/sidebar/worktree-list/grouping/worktree-lineage-projection.test.ts": 51, @@ -8699,7 +8633,6 @@ "src/renderer/src/components/status-bar/use-resource-pty-actions.test.tsx": 879, "src/renderer/src/components/status-bar/use-resource-usage-actions.test.tsx": 746, "src/renderer/src/components/status-bar/use-resource-usage-derived-model.test.tsx": 742, - "src/renderer/src/components/status-bar/workspace-space-breakdown-list.test.tsx": 708, "src/renderer/src/components/status-bar/workspace-space-layout.test.ts": 34, "src/renderer/src/components/status-bar/workspace-space-presentation.test.ts": 448, "src/renderer/src/components/status-bar/workspace-space-worktree-row.test.tsx": 2849, @@ -8906,7 +8839,6 @@ "src/renderer/src/components/terminal-pane/claude-old-terminal-banner.test.tsx": 2146, "src/renderer/src/components/terminal-pane/claude-side-question-completion.test.ts": 2305, "src/renderer/src/components/terminal-pane/closed-terminal-leaf-notice-layout-owner.test.ts": 1032, - "src/renderer/src/components/terminal-pane/closed-terminal-leaf-notice.test.ts": 950, "src/renderer/src/components/terminal-pane/codex-backfill-error-detector.test.ts": 26, "src/renderer/src/components/terminal-pane/codex-detached-pane-restart.test.ts": 2270, "src/renderer/src/components/terminal-pane/codex-restart-main-pane.test.ts": 1753, @@ -8924,7 +8856,6 @@ "src/renderer/src/components/terminal-pane/expand-collapse-render-stability.test.ts": 2069, "src/renderer/src/components/terminal-pane/expand-collapse.test.ts": 102, "src/renderer/src/components/terminal-pane/floating-file-link-selection.test.ts": 2282, - "src/renderer/src/components/terminal-pane/focus-terminal-pane-event.test.ts": 57, "src/renderer/src/components/terminal-pane/focused-pane-rim-flash.test.ts": 46, "src/renderer/src/components/terminal-pane/framed-overlay-terminal-http-links.test.ts": 508, "src/renderer/src/components/terminal-pane/git-bash-console-capacity.test.ts": 56, @@ -8942,7 +8873,6 @@ "src/renderer/src/components/terminal-pane/launch-parity-window-tab.test.ts": 17426, "src/renderer/src/components/terminal-pane/layout-owner-pane-close.test.ts": 2445, "src/renderer/src/components/terminal-pane/layout-serialization.test.ts": 109, - "src/renderer/src/components/terminal-pane/leaf-scrollback-resolution.test.ts": 250, "src/renderer/src/components/terminal-pane/legacy-relay-bridge-transport.test.ts": 358, "src/renderer/src/components/terminal-pane/manual-terminal-worktree-park-eligibility.test.ts": 302, "src/renderer/src/components/terminal-pane/merge-captured-leaf-state.test.ts": 45, @@ -8968,7 +8898,6 @@ "src/renderer/src/components/terminal-pane/park-reveal-live-tui-leaves.test.ts": 42, "src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts": 2837, "src/renderer/src/components/terminal-pane/parked-terminal-command-status.test.ts": 352, - "src/renderer/src/components/terminal-pane/parked-terminal-tab-capture-episodes.test.ts": 265, "src/renderer/src/components/terminal-pane/pending-pane-close-confirmation.test.ts": 4695, "src/renderer/src/components/terminal-pane/pending-runtime-pane-close.test.ts": 3487, "src/renderer/src/components/terminal-pane/pending-split-close.test.ts": 4680, @@ -9076,7 +9005,6 @@ "src/renderer/src/components/terminal-pane/remote-desktop-viewport-claim.test.ts": 45, "src/renderer/src/components/terminal-pane/remote-hidden-output-restore-outcomes.test.ts": 2794, "src/renderer/src/components/terminal-pane/remote-hidden-output-restore-unavailable-banner.repro.test.ts": 2355, - "src/renderer/src/components/terminal-pane/remote-layout-scrollback-retention.test.ts": 70, "src/renderer/src/components/terminal-pane/remote-pane-layout-push.test.ts": 77, "src/renderer/src/components/terminal-pane/remote-park-reveal-unverifiable-retry.test.ts": 1546, "src/renderer/src/components/terminal-pane/remote-reconnect-unimaged-pane-redraw.test.ts": 3122, @@ -9181,7 +9109,6 @@ "src/renderer/src/components/terminal-pane/terminal-drop-upload-report.test.ts": 58, "src/renderer/src/components/terminal-pane/terminal-drop-worktree-path.test.ts": 288, "src/renderer/src/components/terminal-pane/terminal-file-link-actions.test.ts": 482, - "src/renderer/src/components/terminal-pane/terminal-file-link-target.test.ts": 1830, "src/renderer/src/components/terminal-pane/terminal-fit-restore.test.ts": 59, "src/renderer/src/components/terminal-pane/terminal-handle-copy.test.ts": 52, "src/renderer/src/components/terminal-pane/terminal-handle-links.test.ts": 527, @@ -9230,7 +9157,6 @@ "src/renderer/src/components/terminal-pane/terminal-keyboard-native-chat-cover.test.ts": 2084, "src/renderer/src/components/terminal-pane/terminal-keyboard-protocol-pane-agent.test.ts": 48, "src/renderer/src/components/terminal-pane/terminal-kitty-csi-u-encoding.test.ts": 63, - "src/renderer/src/components/terminal-pane/terminal-layout-leaf-ids.test.ts": 55, "src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership-depth.test.ts": 82, "src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership.test.ts": 99, "src/renderer/src/components/terminal-pane/terminal-layout-title-persist.test.tsx": 356, @@ -9257,7 +9183,6 @@ "src/renderer/src/components/terminal-pane/terminal-link-worktree-root-activation.test.ts": 977, "src/renderer/src/components/terminal-pane/terminal-link-wsl-path-mapping.test.ts": 1087, "src/renderer/src/components/terminal-pane/terminal-live-layout-reconciliation.test.ts": 74, - "src/renderer/src/components/terminal-pane/terminal-modify-other-keys-enter.test.ts": 100, "src/renderer/src/components/terminal-pane/terminal-native-copy-gutter.test.ts": 196, "src/renderer/src/components/terminal-pane/terminal-notification-state.test.ts": 1759, "src/renderer/src/components/terminal-pane/terminal-option-kitty-release.test.ts": 52, @@ -9275,7 +9200,6 @@ "src/renderer/src/components/terminal-pane/terminal-pane-recovery-host-rebind-cap.test.ts": 826, "src/renderer/src/components/terminal-pane/terminal-pane-recovery-unsettled-fallback.test.ts": 831, "src/renderer/src/components/terminal-pane/terminal-pane-recovery.test.ts": 949, - "src/renderer/src/components/terminal-pane/terminal-pane-spawn-placement.test.ts": 706, "src/renderer/src/components/terminal-pane/terminal-pane-split-in-main.test.ts": 269, "src/renderer/src/components/terminal-pane/terminal-pane-split-request-routing.test.ts": 2015, "src/renderer/src/components/terminal-pane/terminal-pane-split-with-inherited-cwd.test.ts": 1834, @@ -9332,11 +9256,9 @@ "src/renderer/src/components/terminal-pane/terminal-view-attributes-publisher.test.ts": 333, "src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts": 1669, "src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.test.ts": 48, - "src/renderer/src/components/terminal-pane/terminal-webgl-diagnostics-breadcrumbs.test.ts": 74, "src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts": 123, "src/renderer/src/components/terminal-pane/terminal-worktree-path-link.test.ts": 1878, "src/renderer/src/components/terminal-pane/use-host-terminal-scrollback-hold.test.ts": 256, - "src/renderer/src/components/terminal-pane/use-layout-owner-pane-tree.test.ts": 297, "src/renderer/src/components/terminal-pane/use-mobile-overlay-ticks-desktop-fit.test.tsx": 371, "src/renderer/src/components/terminal-pane/use-notification-dispatch-hidden-workspace.test.ts": 656, "src/renderer/src/components/terminal-pane/use-notification-dispatch.test.ts": 585, @@ -9400,7 +9322,6 @@ "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-editor-close-queue.reveal.test.tsx": 873, "src/renderer/src/components/use-terminal-parking-pass.test.tsx": 2142, "src/renderer/src/components/use-terminal-window-lifecycle.frame-flush.test.tsx": 2164, "src/renderer/src/components/virtualized-list.test.tsx": 446, @@ -9665,7 +9586,6 @@ "src/renderer/src/lib/app-menu-paste.test.ts": 229, "src/renderer/src/lib/automation-session-observer.test.ts": 113, "src/renderer/src/lib/automation-session-reuse.test.ts": 70, - "src/renderer/src/lib/automation-terminal-bind-layout-owner.test.ts": 1756, "src/renderer/src/lib/automation-terminal-ownership.test.ts": 1795, "src/renderer/src/lib/bounded-generation-map.test.ts": 35, "src/renderer/src/lib/browser-cookie-import-error-copy.test.ts": 370, @@ -9676,7 +9596,6 @@ "src/renderer/src/lib/browser-link-profile-isolation.test.ts": 2511, "src/renderer/src/lib/browser-page-palette-activation.test.ts": 1983, "src/renderer/src/lib/browser-palette-page-entries.test.ts": 480, - "src/renderer/src/lib/browser-workspace-tab-activation.test.ts": 1925, "src/renderer/src/lib/bundled-skill-target.test.ts": 54, "src/renderer/src/lib/check-run-details-log-normalization-performance.test.ts": 846, "src/renderer/src/lib/check-run-details-log-normalization.test.ts": 75, @@ -9700,7 +9619,6 @@ "src/renderer/src/lib/connection-context.test.ts": 1817, "src/renderer/src/lib/crash-diagnostics.test.ts": 176, "src/renderer/src/lib/create-untitled-markdown.test.ts": 566, - "src/renderer/src/lib/default-terminal-tabs-applied-persist.test.ts": 1828, "src/renderer/src/lib/desktop-created-server-tabs.test.ts": 1933, "src/renderer/src/lib/direct-ssh-target-scope.test.ts": 48, "src/renderer/src/lib/direct-work-item-setup-callers.test.tsx": 2436, diff --git a/src/main/ai-vault-search/session-search-sidebar-parity.test.ts b/src/main/ai-vault-search/session-search-sidebar-parity.test.ts deleted file mode 100644 index 97a6e924a7a..00000000000 --- a/src/main/ai-vault-search/session-search-sidebar-parity.test.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { afterEach, expect, it } from 'vitest' -import type { AiVaultSession } from '../../shared/ai-vault/contracts/ai-vault-types' -import { filterAiVaultSessions } from '../../shared/ai-vault/session-display/ai-vault-session-filters' -import { - addSyntheticSession, - openSessionSearchHarness, - type SessionSearchHarness -} from './session-search-engine-test-fixture' - -let harness: SessionSearchHarness | null = null - -afterEach(async () => { - await harness?.close() - harness = null -}) - -type Fixture = { id: number; cwd: string; filePath: string; text: string } - -const SESSIONS: Fixture[] = [ - { - id: 1, - cwd: '/Users/Ada/orca/session-search', - filePath: '/Users/Ada/.claude/projects/a/one.jsonl', - text: 'harbor pilot manifest' - }, - { - id: 2, - cwd: '/Users/ada/work/café', - filePath: '/Users/ada/.codex/sessions/two.jsonl', - text: 'harbor dock crane' - }, - { - id: 3, - cwd: '/srv/other/service', - filePath: '/srv/.claude/projects/b/three.jsonl', - text: 'harbor manifest beta' - }, - { - id: 4, - cwd: 'C:\\Work\\Orca\\App', - filePath: 'C:\\Users\\Ada\\.claude\\four.jsonl', - text: 'harbor windows lane' - }, - { - id: 5, - cwd: '/Users/ada/My Project', - filePath: '/Users/ada/.claude/projects/c/five.jsonl', - text: 'harbor quay ledger' - } -] - -const QUERIES = [ - 'harbor path:jsonl', - 'harbor repo:orca/session-search', - 'harbor path:CAFÉ', - 'harbor path:/Users/Ada/orca', - 'harbor repo:app', - 'harbor repo:Orca/App', - 'harbor path:.codex', - 'harbor path:/srv repo:other/service', - 'harbor repo:session-search path:jsonl', - 'harbor path:"/Users/ada/work"', - 'harbor repo:nothing-here', - 'harbor path:one.jsonl path:two.jsonl', - 'harbor path:"/Users/ada/My Project"', - 'harbor repo:"ada/My Project"', - 'harbor' -] - -function asSession(fixture: Fixture): AiVaultSession { - const at = '2026-09-01T00:00:00.000Z' - return { - id: String(fixture.id), - executionHostId: 'local', - agent: 'claude', - sessionId: String(fixture.id), - title: 'fixture', - cwd: fixture.cwd, - branch: null, - model: null, - filePath: fixture.filePath, - codexHome: null, - createdAt: at, - updatedAt: at, - modifiedAt: at, - messageCount: 1, - totalTokens: 0, - previewMessages: [{ role: 'user', text: fixture.text }], - queuedMessageCount: 0, - subagentTranscriptCount: 0, - resumeCommand: '', - subagent: null - } as AiVaultSession -} - -/** Keep the full query so quoted operator values use the panel’s parser. */ -function sidebarIds(query: string): string[] { - return filterAiVaultSessions(SESSIONS.map(asSession), { - query, - agents: ['claude'], - scope: 'all', - sort: 'updated', - activeWorktreePaths: [], - hideEmptySessions: false - }) - .map((session) => session.sessionId) - .sort() -} - -it.each(QUERIES)('answers %s the way the sessions panel does', async (query) => { - harness = await openSessionSearchHarness('ss-sidebar-parity') - for (const fixture of SESSIONS) { - addSyntheticSession(harness.db, { - id: fixture.id, - cwd: fixture.cwd, - text: fixture.text, - filePath: fixture.filePath, - sessionFilePath: fixture.filePath - }) - } - const engineIds = harness.engine - .search({ query, limit: 100 }) - .hits.map((hit) => hit.sessionId) - .sort() - expect(engineIds).toEqual(sidebarIds(query)) -}) - -it('is not vacuous: these queries do select, and reject, real sessions', () => { - const answers = QUERIES.map((query) => sidebarIds(query).length) - expect(answers.some((count) => count > 0 && count < SESSIONS.length)).toBe(true) - expect(answers.some((count) => count === 0)).toBe(true) -}) diff --git a/src/main/codex-accounts/runtime-home-mirrored-status-home.test.ts b/src/main/codex-accounts/runtime-home-mirrored-status-home.test.ts deleted file mode 100644 index 78cdf0c3bdc..00000000000 --- a/src/main/codex-accounts/runtime-home-mirrored-status-home.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/vitest-host-ports-setup' -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type * as NodeOs from 'node:os' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { CodexManagedAccount } from '../../shared/managed-account-types' - -const testState = { userData: '', home: '' } -const previousEnv: Record = {} - -vi.mock('electron', () => ({ app: { getPath: () => testState.userData } })) -beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userData })) -vi.mock('node:os', async () => { - const actual = await vi.importActual('node:os') - return { ...actual, homedir: () => testState.home } -}) - -beforeEach(() => { - vi.resetModules() - testState.userData = mkdtempSync(join(tmpdir(), 'orca-codex-status-home-ud-')) - testState.home = mkdtempSync(join(tmpdir(), 'orca-codex-status-home-')) - // Isolate routing checks from the developer's home overrides. - for (const key of ['ORCA_USER_DATA_PATH', 'CODEX_HOME', 'ORCA_CODEX_HOME']) { - previousEnv[key] = process.env[key] - delete process.env[key] - } - process.env.ORCA_USER_DATA_PATH = testState.userData - mkdirSync(join(testState.home, '.codex'), { recursive: true }) -}) - -afterEach(() => { - rmSync(testState.userData, { recursive: true, force: true }) - rmSync(testState.home, { recursive: true, force: true }) - for (const [key, value] of Object.entries(previousEnv)) { - if (value === undefined) { - delete process.env[key] - } else { - process.env[key] = value - } - } -}) - -function createStore(accounts: CodexManagedAccount[], activeId: string | null) { - const settings = { - codexManagedAccounts: accounts, - activeCodexManagedAccountId: activeId, - activeCodexManagedAccountIdsByRuntime: { host: activeId, wsl: {} } - } as GlobalSettings - return { - getSettings: () => settings, - updateSettings: (updates: Partial) => Object.assign(settings, updates) - } -} - -function createManagedAccount(id: string): CodexManagedAccount { - const home = join(testState.userData, 'codex-accounts', id, 'home') - mkdirSync(home, { recursive: true }) - writeFileSync(join(home, '.orca-managed-home'), `${id}\n`, 'utf-8') - writeFileSync(join(home, 'auth.json'), '{}', 'utf-8') - return { - id, - providerAccountId: id, - email: `${id}@example.com`, - managedHomePath: home, - runtime: 'host' - } as unknown as CodexManagedAccount -} - -describe('CodexRuntimeHomeService.getMirroredHostHomePathForStatus', () => { - it('returns null for the system default, which runs on the real home with no mirror', async () => { - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const service = new CodexRuntimeHomeService(createStore([], null) as never) - - expect(service.getMirroredHostHomePathForStatus()).toEqual({ kind: 'ready', homePath: null }) - }) - - it('returns the selected account own home, which is what its mirror targets', async () => { - const account = createManagedAccount('acct-1') - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const service = new CodexRuntimeHomeService(createStore([account], account.id) as never) - - expect(service.getMirroredHostHomePathForStatus()).toEqual({ - kind: 'ready', - homePath: account.managedHomePath - }) - }) - - it('returns the shared runtime home when a custom CODEX_HOME keeps the mirror lane', async () => { - process.env.CODEX_HOME = join(testState.home, 'custom-codex-home') - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const { getOrcaManagedCodexHomePath } = - await import('../codex/configuration/homes/codex-home-paths') - const service = new CodexRuntimeHomeService(createStore([], null) as never) - - expect(service.getMirroredHostHomePathForStatus()).toEqual({ - kind: 'ready', - homePath: getOrcaManagedCodexHomePath() - }) - }) -}) diff --git a/src/main/codex/configuration/homes/codex-pane-account-registry-mutations.test.ts b/src/main/codex/configuration/homes/codex-pane-account-registry-mutations.test.ts index e7a09ad7a82..bbc80716a14 100644 --- a/src/main/codex/configuration/homes/codex-pane-account-registry-mutations.test.ts +++ b/src/main/codex/configuration/homes/codex-pane-account-registry-mutations.test.ts @@ -68,28 +68,4 @@ describe('CodexPaneAccountRegistryMutations', () => { mutations.flush() expect(parseRegistry(persisted).panes.spawned).toEqual(SPAWNED) }) - - it('retries durability after a write failure even when the cached value now matches', async () => { - const registry = parseRegistry(JSON.stringify({ version: 2, panes: { existing: EXISTING } })) - const write = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true) - const mutations = new CodexPaneAccountRegistryMutations({ read: () => registry, write }) - - mutations.record('spawned', SPAWNED) - await vi.advanceTimersByTimeAsync(100) - - expect(write).toHaveBeenCalledTimes(2) - expect(vi.getTimerCount()).toBe(0) - }) - - it('retries a failed reconciliation write without a pending pane mutation', async () => { - const registry = parseRegistry(JSON.stringify({ version: 2, panes: { existing: EXISTING } })) - const write = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true) - const mutations = new CodexPaneAccountRegistryMutations({ read: () => registry, write }) - - mutations.persistReconciliation(registry, true) - await vi.advanceTimersByTimeAsync(100) - - expect(write).toHaveBeenCalledTimes(2) - expect(vi.getTimerCount()).toBe(0) - }) }) diff --git a/src/main/codex/configuration/homes/codex-windows-sandbox-read-grant.test.ts b/src/main/codex/configuration/homes/codex-windows-sandbox-read-grant.test.ts deleted file mode 100644 index 9fddfd3e7c0..00000000000 --- a/src/main/codex/configuration/homes/codex-windows-sandbox-read-grant.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { runProcessMock } = vi.hoisted(() => ({ runProcessMock: vi.fn() })) -vi.mock('@orca/process-host', () => ({ runProcess: runProcessMock })) - -import { grantCodexSandboxReadOnManagedHome } from './codex-windows-sandbox-read-grant' - -const originalPlatform = process.platform -const originalComputerName = process.env.COMPUTERNAME -let home: string - -function processResult(code: number, stdout = '') { - return { code, signal: null, stdout, stderr: '', timedOut: false } -} - -function grantCalls(): string[] { - return runProcessMock.mock.calls - .map(([spec]) => spec.args) - .filter((args: string[]) => args[1] === '/grant') - .map((args: string[]) => args[0]) -} - -beforeEach(() => { - runProcessMock.mockReset() - runProcessMock.mockResolvedValue(processResult(0)) - home = mkdtempSync(join(tmpdir(), 'codex-sandbox-read-grant-')) - mkdirSync(join(home, '.sandbox')) - writeFileSync(join(home, '.sandbox', 'setup_marker.json'), '{}') - Object.defineProperty(process, 'platform', { value: 'win32' }) - process.env.COMPUTERNAME = 'PC' -}) - -afterEach(() => { - Object.defineProperty(process, 'platform', { value: originalPlatform }) - process.env.COMPUTERNAME = originalComputerName - vi.useRealTimers() - rmSync(home, { recursive: true, force: true }) -}) - -describe('grantCodexSandboxReadOnManagedHome', () => { - it('grants the sandbox group read on the resource folders, never the home root', async () => { - mkdirSync(join(home, 'skills')) - - await grantCodexSandboxReadOnManagedHome(home) - await grantCodexSandboxReadOnManagedHome(home) - - expect(existsSync(join(home, 'generated_images'))).toBe(true) - expect(grantCalls().sort()).toEqual([join(home, 'generated_images'), join(home, 'skills')]) - expect(runProcessMock).toHaveBeenCalledWith( - expect.objectContaining({ - program: expect.stringMatching(/System32[\\/]icacls\.exe$/), - args: [join(home, 'skills'), '/grant', 'PC\\CodexSandboxUsers:(OI)(CI)RX', '/Q'] - }) - ) - }) - - it('retries a failed grant on the next launch', async () => { - runProcessMock.mockImplementation(async ({ args }) => - args[1] === '/grant' ? processResult(1332) : processResult(0) - ) - await grantCodexSandboxReadOnManagedHome(home) - runProcessMock.mockResolvedValue(processResult(0)) - await grantCodexSandboxReadOnManagedHome(home) - - expect(grantCalls()).toEqual([join(home, 'generated_images'), join(home, 'generated_images')]) - }) - - it('does nothing before Codex set up its elevated sandbox for the home', async () => { - rmSync(join(home, '.sandbox'), { recursive: true }) - await grantCodexSandboxReadOnManagedHome(home) - expect(runProcessMock).not.toHaveBeenCalled() - }) - it('skips linked skills and plugins so the grant never reaches the system Codex home', async () => { - const systemHome = mkdtempSync(join(tmpdir(), 'codex-system-home-')) - try { - mkdirSync(join(systemHome, 'skills')) - mkdirSync(join(systemHome, 'plugins')) - symlinkSync(join(systemHome, 'skills'), join(home, 'skills'), 'junction') - symlinkSync(join(systemHome, 'plugins'), join(home, 'plugins'), 'junction') - - await grantCodexSandboxReadOnManagedHome(home) - - expect(grantCalls()).toEqual([join(home, 'generated_images')]) - } finally { - rmSync(systemHome, { recursive: true, force: true }) - } - }) - - it('grants once Codex writes its setup marker during the first elevated session', async () => { - vi.useFakeTimers() - rmSync(join(home, '.sandbox'), { recursive: true }) - writeFileSync(join(home, 'config.toml'), '[windows]\nsandbox = "elevated"\n') - - await grantCodexSandboxReadOnManagedHome(home) - expect(runProcessMock).not.toHaveBeenCalled() - - mkdirSync(join(home, '.sandbox')) - writeFileSync(join(home, '.sandbox', 'setup_marker.json'), '{}') - await vi.advanceTimersByTimeAsync(5_000) - - expect(grantCalls()).toEqual([join(home, 'generated_images')]) - }) -}) diff --git a/src/main/codex/history/index/codex-session-index-heal-state.test.ts b/src/main/codex/history/index/codex-session-index-heal-state.test.ts index bb09a3400ca..45a42e38333 100644 --- a/src/main/codex/history/index/codex-session-index-heal-state.test.ts +++ b/src/main/codex/history/index/codex-session-index-heal-state.test.ts @@ -83,27 +83,6 @@ describe('codex session index heal state', () => { ]) }) - it('leaves the main thread free while walking a large audit ledger', async () => { - const paths = createPaths() - for (let index = 0; index < 20_000; index += 1) { - appendAuditRecord( - paths, - `${WINDOWS_SESSIONS_ROOT}\\2026\\07\\01\\rollout-2026-07-01T10-00-00-019f0000-1111-7222-8333-${String(index).padStart(12, '0')}.jsonl`, - `audit-${index}` - ) - } - let ticks = 0 - const ticker = setInterval(() => { - ticks += 1 - }, 1) - - const pending = await collectPendingHealThreads(paths) - clearInterval(ticker) - - expect(pending).toHaveLength(20_000) - expect(ticks).toBeGreaterThan(0) - }) - it('refuses to treat an unreadable audit ledger as an empty work queue', async () => { const paths = createPaths() mkdirSync(paths.auditLogPath, { recursive: true }) diff --git a/src/main/codex/history/rollouts/codex-rollout-session-meta.test.ts b/src/main/codex/history/rollouts/codex-rollout-session-meta.test.ts index 87b31af2216..799c5123275 100644 --- a/src/main/codex/history/rollouts/codex-rollout-session-meta.test.ts +++ b/src/main/codex/history/rollouts/codex-rollout-session-meta.test.ts @@ -44,34 +44,6 @@ describe('readCodexRolloutSessionMetaId', () => { await expect(readCodexRolloutSessionMetaId(malformed)).resolves.toBeNull() }) - // AI Vault must use the transcript gate to bound stalled WSL reads (#15453). - it('reads through the gated transcript filesystem at interactive priority', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-codex-session-meta-')) - tempRoots.push(root) - const rollout = join(root, 'rollout.jsonl') - await writeFile(rollout, JSON.stringify({ type: 'session_meta', payload: { id: 'gated' } })) - const controller = new AbortController() - - await expect(readCodexRolloutSessionMetaId(rollout, controller.signal)).resolves.toBe('gated') - - // Interactive resume must not queue behind bulk scans. - expect(mocks.readTranscriptSlice).toHaveBeenCalledWith( - rollout, - 0, - expect.any(Number), - 'exact', - controller.signal - ) - await expect(readCodexRolloutSessionMetaId(rollout, undefined, 'scan')).resolves.toBe('gated') - expect(mocks.readTranscriptSlice).toHaveBeenLastCalledWith( - rollout, - 0, - expect.any(Number), - 'scan', - undefined - ) - }) - it('surfaces an aborted read instead of reporting an unprovable rollout', async () => { const root = await mkdtemp(join(tmpdir(), 'orca-codex-session-meta-')) tempRoots.push(root) diff --git a/src/main/daemon/pty-session-id.test.ts b/src/main/daemon/pty-session-id.test.ts index 579b455536f..d95d0ce60d0 100644 --- a/src/main/daemon/pty-session-id.test.ts +++ b/src/main/daemon/pty-session-id.test.ts @@ -8,14 +8,6 @@ import { parsePtySessionId } from '../../shared/terminal/pty/lifecycle/pty-sessi const USER_DATA = '/tmp/orca-userdata' -describe('mintPtySessionId', () => { - it('preserves path-shaped worktreeIds verbatim in the prefix', () => { - // Workspace IDs embed absolute paths; preserve them for @@ ownership parsing. - const id = mintPtySessionId('repo-123::/Users/me/work/wt-1') - expect(id).toMatch(/^repo-123::\/Users\/me\/work\/wt-1@@[0-9a-f]{8}$/) - }) -}) - describe('ptySessionIdForAgentCreateOperation', () => { it('produces a safe session id for a path-shaped worktree', () => { const id = ptySessionIdForAgentCreateOperation('repo::/Users/dev/worktree', 'b'.repeat(43)) diff --git a/src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts b/src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts index 3418c20612e..53bd26da045 100644 --- a/src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts +++ b/src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts @@ -36,49 +36,6 @@ function renderVisible(term: Terminal): string { } describe('#7329 remote-server snapshot corruption', () => { - it('disarms rehydrated mouse modes but keeps bracketed paste after a reattach snapshot', async () => { - const emu = new HeadlessEmulator({ cols: 80, rows: 24 }) - const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) - try { - await emulatorWrite(emu, '\x1b[?2004h\x1b[?1000h\x1b[?1006h') - await emulatorWrite(emu, 'user@host:~$ ') - - const snapshot = emu.getSnapshot({ scrollbackRows: 0 }) - expect(snapshot.rehydrateSequences).toContain('\x1b[?2004h') - expect(snapshot.modes.bracketedPaste).toBe(true) - expect(snapshot.modes.mouseTracking).toBe(true) - - await replayRemoteSnapshot(term, snapshot) - - // Keep the live shell’s bracketed paste while preventing stale mouse reports from becoming shell input. - expect(term.modes.bracketedPasteMode).toBe(true) - expect(term.modes.mouseTrackingMode).toBe('none') - } finally { - emu.dispose() - term.dispose() - } - }) - - it('disarms any-motion (?1003) and pixel-encoded (?1016) mouse modes left by a killed TUI', async () => { - const emu = new HeadlessEmulator({ cols: 80, rows: 24 }) - const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) - try { - await emulatorWrite(emu, '\x1b[?1003h\x1b[?1016h') - await emulatorWrite(emu, 'user@host:~$ ') - - const snapshot = emu.getSnapshot({ scrollbackRows: 0 }) - expect(snapshot.rehydrateSequences).toContain('\x1b[?1003h') - expect(snapshot.rehydrateSequences).toContain('\x1b[?1016h') - - await replayRemoteSnapshot(term, snapshot) - - expect(term.modes.mouseTrackingMode).toBe('none') - } finally { - emu.dispose() - term.dispose() - } - }) - it('drops a mid-escape tail so continuation bytes render literally after reattach', async () => { const emu = new HeadlessEmulator({ cols: 80, rows: 24 }) const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) diff --git a/src/main/daemon/session-conpty-resize-transcript.test.ts b/src/main/daemon/session-conpty-resize-transcript.test.ts index 075cf4d6164..d26b79fb76b 100644 --- a/src/main/daemon/session-conpty-resize-transcript.test.ts +++ b/src/main/daemon/session-conpty-resize-transcript.test.ts @@ -98,11 +98,4 @@ describe('daemon screen through a captured ConPTY resize transcript', () => { expect(lines.filter((line) => line === LONG_LINE)).toHaveLength(1) expect(lines.filter((line) => /\$.*orca@/.test(line))).toEqual([]) }) - - // Control: the Unix grow model pulls history back under ConPTY's repaint. - it('loses or repeats lines without the ConPTY model', async () => { - const lines = await savedLogicalLines('posix-pty') - const numbers = lines.filter((line) => /^\d+$/.test(line)).map(Number) - expect(numbers).not.toEqual(Array.from({ length: 80 }, (_, i) => i + 1)) - }) }) diff --git a/src/main/git/runner-buffer-cancellation.test.ts b/src/main/git/runner-buffer-cancellation.test.ts index 8129e03855e..516a67e9adc 100644 --- a/src/main/git/runner-buffer-cancellation.test.ts +++ b/src/main/git/runner-buffer-cancellation.test.ts @@ -1,4 +1,3 @@ -import { EventEmitter } from 'node:events' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { execFileMock } = vi.hoisted(() => ({ execFileMock: vi.fn() })) @@ -41,30 +40,6 @@ describe('buffered Git cancellation', () => { } }) - it('kills an active child while retaining its admission slot until close', async () => { - const scheduler = new GitAdmissionScheduler({ generalCap: 1, generalHeadroom: 0 }) - _resetGitAdmissionForTests(scheduler) - const child = Object.assign(new EventEmitter(), { - stdout: new EventEmitter(), - stderr: new EventEmitter(), - kill: vi.fn() - }) - execFileMock.mockReturnValue(child) - const controller = new AbortController() - const read = gitExecFileAsyncBuffer(['show', 'HEAD:file'], { - cwd: '/repo', - signal: controller.signal - }) - const rejected = expect(read).rejects.toMatchObject({ name: 'AbortError' }) - await vi.waitFor(() => expect(execFileMock).toHaveBeenCalledOnce()) - controller.abort() - await rejected - expect(child.kill).toHaveBeenCalledOnce() - expect(scheduler.snapshot().budgets.general.baseUsed).toBe(1) - child.emit('close', 0) - await vi.waitFor(() => expect(scheduler.snapshot().budgets.general.baseUsed).toBe(0)) - }) - it('cancels Windows environment readiness without launching Git', async () => { const platform = process.platform Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) diff --git a/src/main/ipc/local-worktree-runtime-options.test.ts b/src/main/ipc/local-worktree-runtime-options.test.ts index 1b3c7969603..6d4885c6a14 100644 --- a/src/main/ipc/local-worktree-runtime-options.test.ts +++ b/src/main/ipc/local-worktree-runtime-options.test.ts @@ -1,22 +1,5 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import '../../shared/worktree/id' -import type { ParsedWorktreeId } from '../../shared/worktree/id' +import { describe, expect, it } from 'vitest' import { WORKTREE_ID_SEPARATOR } from '../../shared/terminal/pty/lifecycle/pty-session-id-format' -import type * as WorktreeIdModule from '../../shared/worktree/id' - -const counter = vi.hoisted(() => ({ splitCalls: 0 })) - -// Count per-row parsing to expose O(repos × rows) rescans. -vi.mock('../../shared/worktree/id', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - splitWorktreeId: (worktreeId: string): ParsedWorktreeId | null => { - counter.splitCalls += 1 - return actual.splitWorktreeId(worktreeId) - } - } -}) const { getLocalRepoForRegisteredWorktree } = await import('./local-worktree-runtime-options') @@ -25,47 +8,20 @@ type TestRepo = { id: string; path: string; connectionId?: string } const makeStore = ( repos: readonly TestRepo[], worktreeIds: readonly string[] -): { store: never; metaScans: () => number } => { - let metaScans = 0 +): { store: never } => { const meta = Object.fromEntries(worktreeIds.map((id) => [id, {}])) const store = { getRepos: () => repos, - getAllWorktreeMeta: () => { - metaScans += 1 - return meta - } + getAllWorktreeMeta: () => meta } - return { store: store as never, metaScans: () => metaScans } + // SAFETY: This fixture supplies the catalog methods used by the repo lookup. + return { store: store as never } } const worktreeId = (repoId: string, path: string): string => `${repoId}${WORKTREE_ID_SEPARATOR}${path}` -beforeEach(() => { - counter.splitCalls = 0 -}) - describe('getLocalRepoForRegisteredWorktree', () => { - it('walks the worktree meta table once, not once per repo', () => { - // Put the owner last to expose scans repeated for earlier repos. - const repoCount = 10 - const rowCount = 200 - const repos = Array.from({ length: repoCount }, (_, i) => ({ - id: `repo-${i}`, - path: `/repos/repo-${i}` - })) - const target = '/repos/repo-9/wt-last' - const worktreeIds = Array.from({ length: rowCount }, (_, i) => - worktreeId(`repo-${i % repoCount}`, `/repos/wt-${i}`) - ) - worktreeIds[rowCount - 1] = worktreeId(`repo-${repoCount - 1}`, target) - const { store, metaScans } = makeStore(repos, worktreeIds) - - expect(getLocalRepoForRegisteredWorktree(store, target, target)?.id).toBe('repo-9') - expect(metaScans()).toBe(1) - expect(counter.splitCalls).toBe(rowCount) - }) - describe('equivalence with the per-repo scan', () => { const repos: TestRepo[] = [ { id: 'first', path: '/repos/first' }, diff --git a/src/main/ipc/runtime-environments/runtime-environment-subscription-layout-recording.test.ts b/src/main/ipc/runtime-environments/runtime-environment-subscription-layout-recording.test.ts deleted file mode 100644 index 26e4e5ac640..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-subscription-layout-recording.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { beforeEach, expect, it, vi } from 'vitest' -import type { subscribeRuntimeEnvironment } from './runtime-environment-transport-routing' - -const mocks = vi.hoisted(() => ({ handle: vi.fn(), on: vi.fn(), subscribe: vi.fn() })) -vi.mock('electron', () => ({ ipcMain: { handle: mocks.handle, on: mocks.on } })) -vi.mock('../../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ - resolveEnvironment: () => ({ id: 'env', pairingRevision: 1, createdAt: 1 }) -})) -vi.mock('./runtime-environment-transport-routing', () => ({ - subscribeRuntimeEnvironment: mocks.subscribe -})) -import { advanceRuntimeEnvironmentTransportGeneration } from './runtime-environment-transport-generation' -import { - registerRuntimeEnvironmentSubscriptionHandlers, - type PendingRuntimeSubscription, - type RetainedRemoteRuntimeSubscription -} from './runtime-environment-subscription-handlers' - -type Callbacks = Parameters[5] - -const sender = { - id: 1, - isDestroyed: () => false, - send: vi.fn(), - on: vi.fn(), - removeListener: vi.fn() -} -const recordLayoutFrame = vi.fn() -const census = { - id: 'stream', - ok: true as const, - result: { type: 'snapshots', snapshots: [] }, - _meta: { runtimeId: 'server' } -} - -async function open(method: string): Promise { - let callbacks: Callbacks | undefined - mocks.subscribe.mockImplementationOnce( - async (...parameters: Parameters) => { - callbacks = parameters[5] - return { requestId: 'request', sendBinary: vi.fn(() => true), close: vi.fn() } - } - ) - const subscribe = mocks.handle.mock.calls.find( - ([name]) => name === 'runtimeEnvironments:subscribe' - )![1] - await subscribe({ sender }, { selector: 'env', method, subscriptionId: method }) - return callbacks! -} - -beforeEach(() => { - vi.clearAllMocks() - mocks.subscribe.mockReset() - registerRuntimeEnvironmentSubscriptionHandlers({ - getUserDataPath: () => '/profile', - remoteRuntimeSubscriptions: new Map(), - pendingSubscriptions: new Map(), - recordLayoutFrame - }) -}) - -it('records the window’s own stream after forwarding it unchanged, opening nothing new', async () => { - const callbacks = await open('session.tabs.subscribeAll') - callbacks.onEvent({ type: 'response', response: census }) - - expect(mocks.subscribe).toHaveBeenCalledOnce() - expect(mocks.subscribe.mock.calls[0]?.[2]).toBe('session.tabs.subscribeAll') - expect(sender.send).toHaveBeenCalledExactlyOnceWith('runtimeEnvironments:subscriptionEvent', { - subscriptionId: 'session.tabs.subscribeAll', - type: 'response', - response: census - }) - expect(recordLayoutFrame).toHaveBeenCalledExactlyOnceWith( - 'env', - 'session.tabs.subscribeAll', - census - ) - expect(sender.send.mock.invocationCallOrder[0]).toBeLessThan( - recordLayoutFrame.mock.invocationCallOrder[0]! - ) -}) - -it('offers the recorder only frames the window was sent', async () => { - const callbacks = await open('session.tabs.subscribeAll') - callbacks.onEvent({ type: 'binary', bytes: new Uint8Array([1]) }) - callbacks.onEvent({ type: 'error', code: 'lost', message: 'lost' }) - // Retired transport frames must reach neither window nor snapshot. - advanceRuntimeEnvironmentTransportGeneration('env') - sender.send.mockClear() - callbacks.onEvent({ type: 'response', response: census }) - expect(sender.send).not.toHaveBeenCalled() - expect(recordLayoutFrame).not.toHaveBeenCalled() -}) diff --git a/src/main/persistence/migrating-orcad-catalog/orcad-source-ownership.test.ts b/src/main/persistence/migrating-orcad-catalog/orcad-source-ownership.test.ts index 2adf89e2115..4cd8d92eb7c 100644 --- a/src/main/persistence/migrating-orcad-catalog/orcad-source-ownership.test.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-source-ownership.test.ts @@ -4,7 +4,6 @@ import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-w import type { ProjectGroup } from '../../../shared/project-group-types' import type { Repo } from '../../../shared/repo-types' import { orcadMigrationCutoverFixture } from '../../ssh/orcad-migration-cutover-fixture' -import { collectOrcadMigrationSourceCatalog } from './orcad-source-catalog' import { subtractOrcadSourceCatalogState } from './orcad-source-catalog-subtraction' import { orcadSourceFolderWorkspaceIds, repoBelongsToOrcadSource } from './orcad-source-ownership' @@ -77,23 +76,6 @@ describe('orcad migration source ownership on a Windows SSH host', () => { ]) }) - it('exports exactly those rows', () => { - const catalog = windowsCatalog() - const exported = collectOrcadMigrationSourceCatalog( - { - getRepos: () => catalog.repos, - getProjectGroups: () => catalog.projectGroups, - getFolderWorkspaces: () => catalog.folderWorkspaces - }, - { id: TARGET } - ) - expect(exported.repositories.map(({ id }) => id)).toEqual(['repo-app', 'repo-unified']) - expect(exported.folderWorkspaces.map(({ id }) => id).sort()).toEqual([ - 'fw-explicit', - 'fw-inferred' - ]) - }) - it('retires a folder owned through its repo even though the repo goes first', () => { const catalog = windowsCatalog() const state = { ...getDefaultPersistedState('C:/Users/Ann'), ...catalog } diff --git a/src/main/persistence/runtime-authored-workspace-session-fields.test.ts b/src/main/persistence/runtime-authored-workspace-session-fields.test.ts index 184f7680c86..f979f018674 100644 --- a/src/main/persistence/runtime-authored-workspace-session-fields.test.ts +++ b/src/main/persistence/runtime-authored-workspace-session-fields.test.ts @@ -55,13 +55,6 @@ describe('preserving runtime-authored workspace session fields', () => { expect(next.clientHostedBrowserPagesByWorktree).toEqual({ 'repo-1::wt-a': [row] }) }) - it('leaves an untouched write alone rather than inventing a field', () => { - const next = session() - - expect(preserveRuntimeAuthoredWorkspaceSessionFields(next, session())).toBe(next) - expect(preserveRuntimeAuthoredWorkspaceSessionFields(next, null)).toBe(next) - }) - it('keeps default-terminal-tab markers a persist snapshot omitted', () => { const next = preserveRuntimeAuthoredWorkspaceSessionFields(session(), { ...session(), diff --git a/src/main/persistence/terminal-topology/closed-pane-binding-fence.test.ts b/src/main/persistence/terminal-topology/closed-pane-binding-fence.test.ts index 21feeef541f..1740f709dfc 100644 --- a/src/main/persistence/terminal-topology/closed-pane-binding-fence.test.ts +++ b/src/main/persistence/terminal-topology/closed-pane-binding-fence.test.ts @@ -90,13 +90,4 @@ describe('the closed-pane fence', () => { create.rollback?.() expect(isClosedPaneFenced('t:b')).toBe(true) }) - - it('records nothing for an unfenced command', () => { - const store = partitions({ [LOCAL]: sessionWith('t', ['a', 'b']) }) - fencedIfLayoutOwner( - () => null, - () => (store.set(LOCAL, sessionWith('t', ['a'])), { value: null }) - )() - expect(isClosedPaneFenced('t:b')).toBe(false) - }) }) diff --git a/src/main/runtime/editor-open-active-group.test.ts b/src/main/runtime/editor-open-active-group.test.ts deleted file mode 100644 index 6216bcf254a..00000000000 --- a/src/main/runtime/editor-open-active-group.test.ts +++ /dev/null @@ -1,115 +0,0 @@ -import './orca-runtime-test-lifecycle.spec' -import { describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from './orca-runtime-test-mocks.spec' -import { - TEST_WORKTREE_ID, - makeRuntimeStoreWithWorkspaceSession -} from './orca-runtime-test-fixtures.spec' -import { openEditorFileThroughLayoutOwner } from './files/editor-open-through-layout-owner' -import { ownedEditorFileId } from '../../shared/workspace-session/workspace-session-pane-ownership' -import { - addWorkspace, - emptySession, - leaf -} from '../../shared/workspace-layout/workspace-layout-session.test-fixture' - -vi.mock('../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -class RuntimeWithEditorOpenGroup extends OrcaRuntimeService { - groupForTest(worktreeId: string): string | undefined { - return this.editorOpenGroupFor(worktreeId) - } -} - -function twoGroupHost() { - const saved = addWorkspace(emptySession(), TEST_WORKTREE_ID, [ - { id: 'g1', tabs: [{ id: 't1', leaves: [[leaf(1)]] }] }, - { id: 'g2', tabs: [{ id: 't2', leaves: [[leaf(2)]] }] } - ]) - const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession(saved) - Object.assign(runtimeStore, { getWorkspaceSessionHostIds: () => ['local'] }) - const runtime = new RuntimeWithEditorOpenGroup(runtimeStore) - const open = () => - openEditorFileThroughLayoutOwner( - { - applyLayoutCommand: (command) => runtime.applyLayoutCommand(command), - groupFor: (id) => runtime.groupForTest(id), - openInWindow: () => { - throw new Error('opened through the window') - } - }, - { worktreeId: TEST_WORKTREE_ID, filePath: '/tmp/worktree-a/a.ts', relativePath: 'a.ts' } - ) - const groupOfFile = () => - getSession().unifiedTabs?.[TEST_WORKTREE_ID]?.find( - (tab) => tab.entityId === ownedEditorFileId('/tmp/worktree-a/a.ts', TEST_WORKTREE_ID, null) - )?.groupId - return { runtime, open, groupOfFile } -} - -describe('a file main opens lands in the group the window shows', () => { - it('the group the window switched to just now, not the saved one', async () => { - const host = twoGroupHost() - host.runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - activeGroupByWorkspace: { [TEST_WORKTREE_ID]: 'g2' } - }) - - await host.open() - - expect(host.groupOfFile()).toBe('g2') - }) - - it("the saved view's group while no window has reported one", async () => { - const host = twoGroupHost() - - await host.open() - - expect(host.groupOfFile()).toBe('g1') - }) -}) - -describe('a file main opens lands in the group a paired desktop shows', () => { - it("the latest desktop's group, then the other's when that one's connection closes", async () => { - const host = twoGroupHost() - host.runtime.reportClientView('desktop-a', { [TEST_WORKTREE_ID]: 'g2' }) - host.runtime.reportClientView('desktop-b', { [TEST_WORKTREE_ID]: 'g1' }) - expect(host.runtime.groupForTest(TEST_WORKTREE_ID)).toBe('g1') - - host.runtime.cleanupSubscriptionsForConnection('desktop-b') - await host.open() - - expect(host.groupOfFile()).toBe('g2') - }) - - it("the saved view's once every reporting desktop has gone", async () => { - const host = twoGroupHost() - host.runtime.reportClientView('desktop-a', { [TEST_WORKTREE_ID]: 'g2' }) - host.runtime.reportClientView('desktop-a', { [TEST_WORKTREE_ID]: 'g2' }) - host.runtime.cleanupSubscriptionsForConnection('desktop-a') - - expect(host.runtime.groupForTest(TEST_WORKTREE_ID)).toBe('g1') - }) - - it('the window, when it reported after the desktop', () => { - const host = twoGroupHost() - host.runtime.reportClientView('desktop-a', { [TEST_WORKTREE_ID]: 'g1' }) - host.runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - activeGroupByWorkspace: { [TEST_WORKTREE_ID]: 'g2' } - }) - - expect(host.runtime.groupForTest(TEST_WORKTREE_ID)).toBe('g2') - }) - it("a desktop's refresh after a reconnect leaves the group another desktop switched to", async () => { - const host = twoGroupHost() - host.runtime.reportClientView('desktop-a', { [TEST_WORKTREE_ID]: 'g2' }) - host.runtime.reportClientView('desktop-b', { [TEST_WORKTREE_ID]: 'g1' }, true) - - await host.open() - - expect(host.groupOfFile()).toBe('g2') - }) -}) diff --git a/src/main/runtime/host-terminal-close-persistence-durability.test.ts b/src/main/runtime/host-terminal-close-persistence-durability.test.ts index 42cd2d079b1..32bad86b3f4 100644 --- a/src/main/runtime/host-terminal-close-persistence-durability.test.ts +++ b/src/main/runtime/host-terminal-close-persistence-durability.test.ts @@ -52,15 +52,6 @@ describe('host-created terminal close durability', () => { rmSync(testState.dir, { recursive: true, force: true }) }) - it('a host-created terminal does NOT push a fresh repo into host-authoritative membership', async () => { - const store = await makeStore() - await store.persistPtyBinding({ worktreeId: WT, tabId: TAB, leafId: LEAF, ptyId: PTY }) - const session = store.getWorkspaceSession() - expect(session.tabsByWorktree?.[WT]?.map((t) => t.id)).toContain(TAB) - // Unarmed, nonsplit repos must keep renderer closes authoritative. - expect(session.terminalTopologyRevisionByRepoId?.[REPO_ID] ?? 0).toBe(0) - }) - it('a renderer close write durably removes the row it persisted', async () => { const store = await makeStore() await store.persistPtyBinding({ worktreeId: WT, tabId: TAB, leafId: LEAF, ptyId: PTY }) @@ -80,27 +71,3 @@ describe('host-created terminal close durability', () => { expect(store.getWorkspaceSession().tabsByWorktree?.[WT]?.map((t) => t.id)).toContain(TAB) }) }) - -/** Census every fence-advancing seam to catch newly introduced create-time arming. */ -describe('topology fence census', () => { - beforeEach(() => { - testState.dir = mkdtempSync(join(tmpdir(), 'orca-fence-census-')) - testStateDirRef.dir = testState.dir - }) - - afterEach(() => { - rmSync(testState.dir, { recursive: true, force: true }) - }) - - it('a second pane in the same tab still does not arm the fence', async () => { - const store = await makeStore() - await store.persistPtyBinding({ worktreeId: WT, tabId: TAB, leafId: LEAF, ptyId: PTY }) - await store.persistPtyBinding({ - worktreeId: WT, - tabId: TAB, - leafId: '22222222-2222-4222-8222-222222222222', - ptyId: `${PTY}-b` - }) - expect(store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.[REPO_ID] ?? 0).toBe(0) - }) -}) diff --git a/src/main/runtime/orca-runtime-provider-reattach-launch-identity.test.ts b/src/main/runtime/orca-runtime-provider-reattach-launch-identity.test.ts deleted file mode 100644 index 37becd1d090..00000000000 --- a/src/main/runtime/orca-runtime-provider-reattach-launch-identity.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' -import { OrcaRuntimeService } from './orca-runtime' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../shared/layout-owner-switch' -import { registerBoundPty } from './bind-first-pane.test-fixture' -import { partialRuntimeStore } from './runtime-store-partial-fixture' - -vi.mock('electron', () => ({ - app: { getPath: vi.fn(() => '/tmp'), isPackaged: false }, - BrowserWindow: { fromId: vi.fn(() => null) }, - ipcMain: { on: vi.fn(), removeListener: vi.fn() }, - webContents: { fromId: vi.fn(() => null) } -})) - -const TAB_ID = '11111111-1111-4111-8111-111111111111' -const LEAF_ID = '22222222-2222-4222-8222-222222222222' -const PANE_KEY = makePaneKey(TAB_ID, LEAF_ID) -const INCARNATION_ID = 'provider-reattach-incarnation' -const WORKTREE_ID = 'repo-1::/tmp/provider-reattach' - -type RuntimePtyLaunchIdentity = { - incarnationId: string | null - paneKey: string | null - launchAgent: string | null - launchToken: string | null - launchIncarnationId: string | null -} - -function getPty(runtime: OrcaRuntimeService, ptyId: string): RuntimePtyLaunchIdentity | undefined { - return (runtime as unknown as { ptysById: Map }).ptysById.get( - ptyId - ) -} - -// Main-owned layout requires a store to resolve pane/PTY bindings. -function createRuntime(): OrcaRuntimeService { - return new OrcaRuntimeService(ORCA_LAYOUT_OWNER_IS_MAIN ? partialRuntimeStore() : null) -} - -function paneKeyOf(runtime: OrcaRuntimeService, ptyId: string): string | null { - const pty = runtime['ptysById'].get(ptyId) - return runtime['paneOfPty'](pty).paneKey -} - -describe('provider reattach launch identity', () => { - it('restores daemon-owned agent identity without minting renderer authority', () => { - const runtime = createRuntime() - - registerBoundPty(runtime, 'pty-reattach', WORKTREE_ID, null, { - tabId: TAB_ID, - leafId: LEAF_ID, - incarnationId: INCARNATION_ID, - providerReattachLaunchIdentity: { - incarnationId: INCARNATION_ID, - launchAgent: 'codex' - } - }) - - expect(paneKeyOf(runtime, 'pty-reattach')).toBe(PANE_KEY) - expect(getPty(runtime, 'pty-reattach')).toMatchObject({ - incarnationId: INCARNATION_ID, - launchAgent: 'codex', - launchToken: null, - launchIncarnationId: null - }) - }) - - it('rejects provider identity from a different process incarnation', () => { - const runtime = createRuntime() - - registerBoundPty(runtime, 'pty-mismatched-reattach', WORKTREE_ID, null, { - tabId: TAB_ID, - leafId: LEAF_ID, - incarnationId: INCARNATION_ID, - providerReattachLaunchIdentity: { - incarnationId: 'stale-provider-incarnation', - launchAgent: 'codex' - } - }) - - expect(paneKeyOf(runtime, 'pty-mismatched-reattach')).toBe(PANE_KEY) - expect(getPty(runtime, 'pty-mismatched-reattach')).toMatchObject({ - incarnationId: INCARNATION_ID, - launchAgent: null, - launchToken: null, - launchIncarnationId: null - }) - }) - - it('retires daemon launch identity when the agent command finishes', () => { - const runtime = createRuntime() - - registerBoundPty(runtime, 'pty-finished-reattach', WORKTREE_ID, null, { - tabId: TAB_ID, - leafId: LEAF_ID, - incarnationId: INCARNATION_ID, - providerReattachLaunchIdentity: { - incarnationId: INCARNATION_ID, - launchAgent: 'codex' - } - }) - runtime.emitDaemonPtyTransientFact('pty-finished-reattach', { - kind: 'command-finished', - exitCode: 0 - }) - - expect(getPty(runtime, 'pty-finished-reattach')).toMatchObject({ - launchAgent: null, - launchToken: null, - launchIncarnationId: null - }) - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/decorative-title-fact-throttle.spec.ts b/src/main/runtime/orca-runtime-tests/decorative-title-fact-throttle.spec.ts index 6a3c7c886d7..b954719f12d 100644 --- a/src/main/runtime/orca-runtime-tests/decorative-title-fact-throttle.spec.ts +++ b/src/main/runtime/orca-runtime-tests/decorative-title-fact-throttle.spec.ts @@ -2,9 +2,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { TerminalSideEffectBatch } from '../../../shared/terminal/output/terminal-side-effect-facts' import { syncSinglePty } from '../orca-runtime-test-fixtures.spec' import { createSideEffectRuntime } from '../orca-runtime-test-scenario-builders.spec' -import { DECORATIVE_TITLE_FACT_HEARTBEAT_MS } from '../decorative-title-fact-emission' - -const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] const SPINNER_INTERVAL_MS = 80 const EPOCH = 1_700_000_000_000 @@ -26,33 +23,6 @@ describe('decorative title fact throttle', () => { vi.useRealTimers() }) - it('collapses spinner ticks with an unchanged underlying title to the heartbeat rate', () => { - const { runtime, batches } = createSideEffectRuntime() - syncSinglePty(runtime) - - const ticks = 125 - for (let tick = 0; tick < ticks; tick += 1) { - vi.setSystemTime(new Date(EPOCH + tick * SPINNER_INTERVAL_MS)) - runtime.ingestSyntheticTitleFrame( - 'pty-1', - `\x1b]0;${SPINNER_FRAMES[tick % SPINNER_FRAMES.length]} Claude Code\x07` - ) - } - - const facts = titleFacts(batches) - // Identical underlying titles add no information between heartbeats. - const elapsedMs = ticks * SPINNER_INTERVAL_MS - expect(facts.length).toBeLessThanOrEqual( - Math.ceil(elapsedMs / DECORATIVE_TITLE_FACT_HEARTBEAT_MS) - ) - expect(facts.length).toBeLessThan(ticks / 5) - // Three working frames per 1500ms are needed to cancel renderer milestone-done quiet windows. - expect(facts.length).toBeGreaterThanOrEqual(Math.floor(elapsedMs / 1_500) * 3) - for (const fact of facts) { - expect(fact.normalizedTitle.endsWith('Claude Code')).toBe(true) - } - }) - it('propagates a changed working label immediately even while the spinner rotates', () => { // Only spinner glyphs are decorative; Grok/Pi label churn changes content. const { runtime, batches } = createSideEffectRuntime() diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-worktree-creation.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-worktree-creation.test.ts deleted file mode 100644 index 86699892d07..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-worktree-creation.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { MARINE_CREATURES } from '../../../../../../shared/marine-creatures' -import { isAutoGeneratedCreatureBranchName } from '../../../../../../shared/source-control/ai/naming/branch-name-from-work' -import { - creatureNameAtTier, - creatureNameTier -} from '../../../../../../shared/worktree/retired-name-registry' -import { createWorkerWorktree, resolveWorkerWorktreeName } from './worker-worktree-creation' -import type { WorkerEffect } from './worker-topology' - -const pool = MARINE_CREATURES.map((name) => name.toLowerCase()) - -function namingRuntime(livePaths: string[], retired: string[] = [], exhaustedTiers = 0) { - return { - listManagedWorktrees: vi.fn(async () => ({ - worktrees: livePaths.map((path) => ({ path })) - })), - listRetiredWorktreeNames: vi.fn(async () => ({ - retiredNamesByRepo: { repo: retired }, - retiredNameTiersByRepo: { repo: exhaustedTiers } - })) - } -} - -describe('resolveWorkerWorktreeName', () => { - it('keeps an explicit --name without generating one', async () => { - const runtime = namingRuntime([]) - await expect(resolveWorkerWorktreeName(runtime, 'id:repo', 'billing-audit')).resolves.toEqual({ - name: 'billing-audit' - }) - expect(runtime.listManagedWorktrees).not.toHaveBeenCalled() - }) - - it('picks the one creature name no live or retired workspace holds', async () => { - const [free, ...taken] = pool - const half = Math.floor(taken.length / 2) - const runtime = namingRuntime( - taken.slice(0, half).map((name) => `/worktrees/other-repo/${name}`), - taken.slice(half) - ) - await expect(resolveWorkerWorktreeName(runtime, 'id:repo', undefined)).resolves.toEqual({ - name: free, - nameWasGenerated: true - }) - expect(runtime.listRetiredWorktreeNames).toHaveBeenCalledWith('id:repo') - }) - - it('skips tiers the retired registry compacted as spent', async () => { - const result = await resolveWorkerWorktreeName(namingRuntime([], [], 2), 'id:repo', undefined) - expect(creatureNameTier(result.name)).toBe(3) - expect(isAutoGeneratedCreatureBranchName(result.name)).toBe(true) - }) - - it('moves to the next tier once every first-tier name is used', async () => { - const result = await resolveWorkerWorktreeName(namingRuntime([], pool), 'id:repo', undefined) - expect(pool.map((name) => creatureNameAtTier(name, 2))).toContain(result.name) - }) -}) - -describe('createWorkerWorktree naming', () => { - async function create(name: string | undefined) { - const createManagedWorktree = vi.fn(async (_args: Record) => ({ - worktree: { id: 'repo::/worktrees/repo/otter', repoId: 'repo', displayName: 'otter' }, - startupTerminal: { handle: 'term_worker' } - })) - const runtime = { - ...namingRuntime([]), - createManagedWorktree, - listTerminals: vi.fn(async () => ({ terminals: [] })) - } - const effects: WorkerEffect[] = [] - await createWorkerWorktree({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: createWorkerWorktree reaches only the runtime methods faked above. - runtime: runtime as never, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: createWorkerWorktree only records stages on the db. - db: { recordWorkerStage: vi.fn() } as never, - dispatchId: 'ctx_1', - requestedWorktree: 'new-child', - target: { repoSelector: 'id:repo', parentWorktreeId: 'repo::/repo' }, - params: { name, from: 'term_coord' }, - agent: 'codex', - withAgentTerminal: true, - effects - }) - return { request: createManagedWorktree.mock.calls[0][0], effects } - } - - it('creates a generated name the first-work rename may replace, and names it in effects', async () => { - const { request, effects } = await create(undefined) - expect(request.nameWasGenerated).toBe(true) - expect(isAutoGeneratedCreatureBranchName(String(request.name))).toBe(true) - expect(effects[0]).toEqual({ - kind: 'worktree', - action: 'created_child', - id: 'repo::/worktrees/repo/otter', - name: 'otter' - }) - }) - - it('passes an explicit --name through as a user name', async () => { - const { request } = await create('billing-audit') - expect(request.name).toBe('billing-audit') - expect(request).not.toHaveProperty('nameWasGenerated') - }) -}) diff --git a/src/main/runtime/runtime-terminal-orphan-adoption-duplicate-pty.test.ts b/src/main/runtime/runtime-terminal-orphan-adoption-duplicate-pty.test.ts index 6f72b5ed7d6..cf323ef1e0f 100644 --- a/src/main/runtime/runtime-terminal-orphan-adoption-duplicate-pty.test.ts +++ b/src/main/runtime/runtime-terminal-orphan-adoption-duplicate-pty.test.ts @@ -11,7 +11,6 @@ import { emptySession, leaf } from '../../shared/workspace-layout/workspace-layout-session.test-fixture' -import { planDuplicatePtyPaneRepair } from '../persistence/terminal-topology/duplicate-pty-pane-repair' import { adoptRuntimeTerminalOrphansFromInventory } from './runtime-terminal-orphan-adoption' import type { RuntimePtyWorktreeRecord } from './runtime-terminal-state-records' import { paneOfPty } from './terminal/surface/pty-pane-query' @@ -105,12 +104,4 @@ describe('orphan adoption of a terminal main repaired at load', () => { 'terminal_orphan_competing_owner' ) }) - - it('replays the kept pane once the stored tree holds one pane per terminal', async () => { - const repaired = planDuplicatePtyPaneRepair(duplicateSession())!.session - const { adopted, replayPersistedSurface } = adoptKeptPane(repaired) - - await expect(adopted).resolves.toMatchObject({ adopted: false }) - expect(replayPersistedSurface).toHaveBeenCalledWith(expect.anything(), TAB, `${TAB}:${KEPT}`) - }) }) diff --git a/src/main/runtime/terminal-image-viewer-env.test.ts b/src/main/runtime/terminal-image-viewer-env.test.ts index dfafec66ec5..e24b982fb7a 100644 --- a/src/main/runtime/terminal-image-viewer-env.test.ts +++ b/src/main/runtime/terminal-image-viewer-env.test.ts @@ -53,11 +53,6 @@ describe('Claude images follow the launching viewer', () => { ])('keeps same-build local launches on their existing policy %#', (context) => { expect(terminalImageViewerSupported(context)).toBeUndefined() }) - it.each([undefined, true])('keeps supported or local env unchanged (%s)', (supported) => { - vi.stubEnv('CLAUDE_CODE_FORCE_TERMINAL_IMAGES', undefined) - const launch = { launchAgent: 'claude' as const, env: { KEEP: 'yes' } } - expect(applyClaudeTerminalImageViewerEnv(launch, supported)).toBe(launch) - }) it('disables automatic image forcing only for unsupported Claude', () => { vi.stubEnv('CLAUDE_CODE_FORCE_TERMINAL_IMAGES', undefined) const launch = { launchAgent: 'claude' as const, env: { KEEP: 'yes' } } @@ -69,15 +64,4 @@ describe('Claude images follow the launching viewer', () => { const codex = { launchAgent: 'codex' as const } expect(applyClaudeTerminalImageViewerEnv(codex, false)).toBe(codex) }) - it.each(['0', '1', ''])('preserves explicit and inherited override %j', (value) => { - vi.stubEnv('CLAUDE_CODE_FORCE_TERMINAL_IMAGES', undefined) - const explicit = { - launchAgent: 'claude' as const, - env: { CLAUDE_CODE_FORCE_TERMINAL_IMAGES: value } - } - expect(applyClaudeTerminalImageViewerEnv(explicit, false)).toBe(explicit) - vi.stubEnv('CLAUDE_CODE_FORCE_TERMINAL_IMAGES', value) - const inherited = { launchAgent: 'claude' as const } - expect(applyClaudeTerminalImageViewerEnv(inherited, false)).toBe(inherited) - }) }) diff --git a/src/main/runtime/workspace-layout-live-titles.test.ts b/src/main/runtime/workspace-layout-live-titles.test.ts index 3e711e4c330..f8283b4a810 100644 --- a/src/main/runtime/workspace-layout-live-titles.test.ts +++ b/src/main/runtime/workspace-layout-live-titles.test.ts @@ -85,21 +85,4 @@ describe('live pane titles on the layout stream', () => { await flush() expect(events).toHaveLength(1) }) - - it('sends no frame per spinner glyph while an agent works', async () => { - const runtime = runtimeWithPane() - const collector = collectLayoutEvents() - const { events } = collector - collector.seed(runtime.subscribeWorkspaceLayouts(collector.listener).snapshot) - const spinner = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] - for (let frame = 0; frame < 100; frame++) { - runtime.onPtyData( - PTY_ID, - `\x1b]0;${spinner[frame % spinner.length]} Fix the build\x07`, - Date.now() - ) - await flush() - } - expect(events.map((event) => paneOf(event)?.liveTitle)).toEqual(['⠋ Fix the build']) - }) }) diff --git a/src/main/ssh/orcad-unreachable-setup-stop.test.ts b/src/main/ssh/orcad-unreachable-setup-stop.test.ts deleted file mode 100644 index c15fd2d2bff..00000000000 --- a/src/main/ssh/orcad-unreachable-setup-stop.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { emptyOrcadActivationRecord } from '../managed-server/activation/orcad-activation-record' - -const mocks = vi.hoisted(() => { - const record: { active: string | null } = { active: '1.0.0+a' } - return { stop: vi.fn(), write: vi.fn(), release: vi.fn(), record } -}) -vi.mock('../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ - listEnvironments: () => [] -})) -vi.mock('../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store', () => ({ - removeManagedOrcadEnvironment: vi.fn() -})) -vi.mock('./orcad-migration-cutover-journal', () => ({ - findOrcadMigrationSourceCutoverForTarget: () => ({ - phase: 'source-fenced', - destinationEnvironmentId: 'env-1' - }) -})) -vi.mock('./orcad-migration-source-fence', () => ({ - releaseUndeployedMigrationFence: mocks.release -})) -vi.mock('../managed-server/lifecycle/orcad-managed-tunnel', () => ({ - closeOrcadManagedTunnel: async () => undefined -})) -vi.mock('./targets/ssh-target-registry', () => ({ - getSshTargetRegistryStore: () => ({ getTarget: () => ({ id: 'ssh-1' }) }), - getSshConnectionManager: () => ({ connect: async () => ({}) }) -})) -vi.mock('../managed-server/install/orcad-remote-context', () => ({ - resolveOrcadRemoteContext: async () => ({ - activationRecord: { ...emptyOrcadActivationRecord(), active: mocks.record.active }, - connection: {}, - host: { os: 'linux' }, - remoteHome: '/home/u', - userDataDir: '/home/u/.orca' - }) -})) -vi.mock('../managed-server/activation/orcad-activation-lock', () => ({ - withOrcadActivationLock: async (_options: unknown, run: () => Promise) => run() -})) -vi.mock('../managed-server/activation/orcad-activation-record-store', () => ({ - readOrcadActivationRecord: async () => ({ - ...emptyOrcadActivationRecord(), - active: mocks.record.active - }), - writeOrcadActivationRecord: mocks.write -})) -vi.mock('./orcad-recovery-slot', () => ({ - orcadSlotDir: (_slot: unknown, version: string) => `/slots/${version}`, - stopOrcadSlot: mocks.stop -})) - -const { releaseUnreachableOrcadSetup } = await import('./orcad-unreachable-setup-release') -const release = () => - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: claims pass through to the mocked fence release only. - releaseUnreachableOrcadSetup({ userDataPath: '/u', claims: {} as never, targetId: 'ssh-1' }) - -beforeEach(() => { - vi.clearAllMocks() - mocks.record.active = '1.0.0+a' -}) - -describe('releasing an unreachable setup', () => { - it('stops the orcad it activated and clears active only on proven exit', async () => { - mocks.stop.mockResolvedValueOnce('stopped') - await release() - expect(mocks.stop).toHaveBeenCalledWith(expect.anything(), '/slots/1.0.0+a', false) - expect(mocks.write.mock.calls[0]?.[1]).toMatchObject({ active: null, previous: '1.0.0+a' }) - expect(mocks.release).toHaveBeenCalledOnce() - }) - - it('keeps the record when the stop is not proven, and still releases the fence', async () => { - mocks.stop.mockResolvedValueOnce('unconfirmed') - await release() - expect(mocks.write).not.toHaveBeenCalled() - expect(mocks.release).toHaveBeenCalledOnce() - }) - - it('touches nothing on a host whose setup never activated', async () => { - mocks.record.active = null - await release() - expect(mocks.stop).not.toHaveBeenCalled() - expect(mocks.release).toHaveBeenCalledOnce() - }) -}) diff --git a/src/renderer/src/app-shell/app-command-handlers-workspace-delete.test.ts b/src/renderer/src/app-shell/app-command-handlers-workspace-delete.test.ts deleted file mode 100644 index 50d93ac8895..00000000000 --- a/src/renderer/src/app-shell/app-command-handlers-workspace-delete.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { AppState } from '@/store/types' -import type { HoveredWorkspaceDeleteTarget } from '../components/sidebar/workspace-actions/deletion/hovered-workspace-delete' -import type { AppShortcutState, ShortcutDispatchInput } from './app-command-handlers' - -const mocks = vi.hoisted(() => ({ - deleteHoveredWorkspaceImmediately: vi.fn(), - hoveredTarget: { kind: 'worktree', worktree: {} } as HoveredWorkspaceDeleteTarget | null, - store: {} as AppState -})) - -vi.mock('../store', () => ({ - useAppStore: Object.assign(vi.fn(), { getState: () => mocks.store }) -})) - -vi.mock('../components/sidebar/workspace-actions/deletion/hovered-workspace-delete', () => ({ - deleteHoveredWorkspaceImmediately: mocks.deleteHoveredWorkspaceImmediately, - resolveHoveredWorkspaceDeleteTarget: () => mocks.hoveredTarget -})) - -vi.mock('@/lib/floating-workspace-terminal-actions', () => ({ - isFloatingWorkspacePanelFocused: () => false -})) - -vi.mock('@/lib/terminal-shortcut-capture-notification', () => ({ - showTerminalShortcutCaptureNotification: vi.fn() -})) - -import { createAppCommandHandlers } from './app-command-handlers' - -function shortcutState(overrides: Partial = {}): AppShortcutState { - return { - activeView: 'terminal', - activeWorktreeId: 'repo::/feature', - 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, - ...overrides - } -} - -function shortcutInput(): ShortcutDispatchInput { - return { - target: null, - defaultPrevented: false, - preventDefault: vi.fn() - } -} - -describe('workspace delete app command', () => { - beforeEach(() => { - vi.clearAllMocks() - mocks.store = { activeWorktreeId: 'repo::/feature' } as AppState - mocks.hoveredTarget = { kind: 'worktree', worktree: {} as never } - }) - - it('claims the chord and immediately deletes the hovered workspace', () => { - const input = shortcutInput() - const handler = createAppCommandHandlers(shortcutState(), input, 'terminal').get( - 'workspace.delete' - ) - - expect(handler?.()).toBe(true) - expect(input.preventDefault).toHaveBeenCalledOnce() - expect(mocks.deleteHoveredWorkspaceImmediately).toHaveBeenCalledWith( - mocks.store, - mocks.hoveredTarget - ) - }) - - it('does not claim the chord without a hovered workspace', () => { - const input = shortcutInput() - const handler = createAppCommandHandlers(shortcutState(), input).get('workspace.delete') - - mocks.hoveredTarget = null - expect(handler?.()).toBe(false) - expect(input.preventDefault).not.toHaveBeenCalled() - expect(mocks.deleteHoveredWorkspaceImmediately).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/NewWorkspaceComposerCard.set-location-warm.test.tsx b/src/renderer/src/components/NewWorkspaceComposerCard.set-location-warm.test.tsx deleted file mode 100644 index fb63aa47e08..00000000000 --- a/src/renderer/src/components/NewWorkspaceComposerCard.set-location-warm.test.tsx +++ /dev/null @@ -1,120 +0,0 @@ -// @vitest-environment happy-dom - -import React from 'react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { hostOptions, renderCard } from './NewWorkspaceComposerCard.test-fixture' -import type { ProjectHostSetupOption } from '@/lib/project-host-setup-options' - -// Count module evaluation so tests detect whether the composer requests the chunk. -const chunk = vi.hoisted(() => ({ loads: 0 })) - -// Render a marker so warming-without-mounting assertions cannot pass vacuously. -vi.mock('@/components/new-workspace/SetProjectLocationDialog', () => { - chunk.loads += 1 - return { - SetProjectLocationDialog: () =>
- } -}) - -vi.mock('@/store', () => ({ - useAppStore: Object.assign( - (selector: (state: unknown) => unknown) => - selector({ - closeModal: vi.fn(), - openModal: vi.fn(), - openSettingsPage: vi.fn(), - openSettingsTarget: vi.fn(), - setRuntimeEnvironmentStatus: vi.fn(), - setupProjectExistingFolder: vi.fn(), - setupProjectClone: vi.fn(), - activeModal: 'new-workspace-composer', - settings: { defaultTuiAgent: null, disabledTuiAgents: [] }, - updateSettings: vi.fn(), - projects: [], - repos: [] - }), - { getState: () => ({}) } - ) -})) - -vi.mock('@/components/contextual-tours/use-contextual-tour', () => ({ - useContextualTour: vi.fn() -})) - -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}, - TooltipContent: ({ children }: { children: React.ReactNode }) => <>{children}, - TooltipTrigger: ({ children }: { children: React.ReactNode }) => <>{children} -})) - -vi.mock('@/components/agent/AgentCombobox', () => ({ - default: () => -})) - -vi.mock('@/components/sidebar/host-admission/ssh/AddRemoteHostDialog', () => ({ - AddRemoteHostDialog: () => null -})) - -vi.mock('@/components/sparse/SparseCheckoutPresetSelect', () => ({ - default: () => null -})) - -vi.mock('@/components/new-workspace/SmartWorkspaceNameField', () => ({ - default: () => -})) - -vi.mock('@/components/new-workspace/ProjectCombobox', () => ({ - default: () =>
-})) - -const readyOnlyHostOptions = hostOptions.filter((option) => option.kind === 'ready') -// A disconnected host is a needs-setup row with no "Set location" action, so it must not warm. -const unavailableHostOptions: ProjectHostSetupOption[] = [ - ...readyOnlyHostOptions, - { - kind: 'needs-setup', - id: 'needs-setup:ssh:offline', - projectId: 'project-group:platform', - hostId: 'ssh:offline', - label: 'Offline box', - detail: 'Not connected', - isAvailable: false, - attention: false, - canSetLocation: false - } -] - -// Run no-warm cases first: dynamic import evaluates the shared module only once. -describe('NewWorkspaceComposerCard set-location chunk warm', () => { - let container: HTMLDivElement | null = null - - afterEach(() => { - container?.remove() - container = null - }) - - it('does not warm the chunk when no host needs its location set', async () => { - container = await renderCard({ projectHostSetupOptions: readyOnlyHostOptions }) - - expect( - [...container.querySelectorAll('button')].some((button) => - button.textContent?.includes('Set project location') - ) - ).toBe(false) - expect(chunk.loads).toBe(0) - }) - - it('does not warm the chunk when the needs-setup host cannot take a location', async () => { - container = await renderCard({ projectHostSetupOptions: unavailableHostOptions }) - - expect(chunk.loads).toBe(0) - }) - - it('warms the chunk on mount for a needs-setup host, before Set project location is clicked', async () => { - container = await renderCard() - - expect(chunk.loads).toBe(1) - // Warming must not mount the dialog; it still waits on an explicit click. - expect(document.body.querySelector('[data-testid="set-project-location-dialog"]')).toBeNull() - }) -}) diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-extension-menu-items.test.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-extension-menu-items.test.tsx deleted file mode 100644 index 13949bdfd2b..00000000000 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-extension-menu-items.test.tsx +++ /dev/null @@ -1,89 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { BrowserExtensionContextMenuPayload } from '../../../../../shared/browser/extensions/browser-extension-context-menu-types' -import { BrowserPageExtensionMenuItems } from './browser-page-extension-menu-items' - -const VAULT = 'a'.repeat(32) -const NOTES = 'b'.repeat(32) -const leaf = (key: string, title: string) => ({ - key, - title, - type: 'normal' as const, - checked: false, - enabled: true, - children: [] -}) - -const menu: BrowserExtensionContextMenuPayload = { - token: 'token-1', - groups: [ - { extensionId: NOTES, items: [leaf('7', 'Save to notes')] }, - { - extensionId: VAULT, - items: [ - { - ...leaf('', 'Vault'), - children: [ - leaf('"fill"', 'Fill'), - { ...leaf('"remember"', 'Remember'), type: 'checkbox', checked: true } - ] - } - ] - } - ] -} - -let root: Root -let container: HTMLDivElement -const click = vi.fn(async () => true) -const done = vi.fn() - -beforeEach(() => { - container = document.createElement('div') - document.body.append(container) - root = createRoot(container) - Object.assign(window, { api: { browser: { extensionsContextMenuClick: click } } }) - act(() => { - root.render() - }) -}) - -afterEach(() => { - act(() => root.unmount()) - container.remove() - click.mockClear() - done.mockClear() -}) - -function item(name: string): HTMLElement { - const found = [...container.querySelectorAll('[role^="menuitem"]')].find( - (element) => element.textContent?.trim() === name - ) - if (!found) { - throw new Error(`No menu item ${name}`) - } - return found -} - -describe('extension items in the page context menu', () => { - it('shows a single item inline and several under the extension submenu', () => { - expect(item('Save to notes').getAttribute('aria-haspopup')).toBeNull() - expect(item('Vault').getAttribute('aria-haspopup')).toBe('menu') - expect(container.textContent).not.toContain('Fill') - - act(() => item('Vault').click()) - expect(item('Fill')).toBeTruthy() - expect(item('Remember').getAttribute('role')).toBe('menuitemcheckbox') - expect(item('Remember').getAttribute('aria-checked')).toBe('true') - }) - - it('sends the token, extension and item key, then closes the menu', () => { - act(() => item('Vault').click()) - act(() => item('Fill').click()) - expect(click).toHaveBeenCalledWith({ token: 'token-1', extensionId: VAULT, key: '"fill"' }) - expect(done).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/renderer/src/components/browser-pane/browser-client-page-renderer-installation.test.ts b/src/renderer/src/components/browser-pane/browser-client-page-renderer-installation.test.ts deleted file mode 100644 index 33a718f99fe..00000000000 --- a/src/renderer/src/components/browser-pane/browser-client-page-renderer-installation.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { - BrowserClientPageRendererOutcome, - BrowserClientPageRendererRequest -} from '../../../../shared/browser/client-hosting/browser-client-page-renderer-protocol' -import { installBrowserClientPageRenderer } from './browser-client-page-renderer-installation' - -const PAGE = { - partition: 'persist:route-a', - browserPageId: 'page-a', - pageHostGeneration: 7 -} - -type RequestCallback = ( - request: BrowserClientPageRendererRequest -) => BrowserClientPageRendererOutcome | Promise - -describe('browser client page renderer installation', () => { - afterEach(() => { - delete (window as unknown as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ - }) - - it('stays inert when the preload surface is unavailable', () => { - expect(installBrowserClientPageRenderer({ subscribe: undefined })).toBeNull() - }) - - it('stays inert in the paired web client', () => { - ;(window as unknown as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ = true - const subscribe = vi.fn() - - expect(installBrowserClientPageRenderer({ subscribe })).toBeNull() - expect(subscribe).not.toHaveBeenCalled() - }) - - it('routes mount, rekey, and idempotent retirement through one subscriber', async () => { - let callback: RequestCallback | null = null - const unsubscribe = vi.fn() - const subscribe = vi.fn((next: typeof callback) => { - callback = next - return unsubscribe - }) - const registry = { - dispose: vi.fn(), - getMemoryProfile: vi.fn(() => ({ - retainedPageCount: 1, - attachingPageCount: 0, - attachedPageCount: 1, - retiringPageCount: 0, - partitionCount: 1 - })), - mountPage: vi.fn(async () => ({ webContentsId: 41 })), - rekeyPage: vi.fn(), - retirePage: vi.fn() - } - const installation = installBrowserClientPageRenderer({ registry, subscribe })! - - await expect( - Promise.resolve(callback!({ requestId: 'mount-a', type: 'mountPage', page: PAGE })) - ).resolves.toEqual({ type: 'mounted', webContentsId: 41 }) - const nextPage = { ...PAGE, pageHostGeneration: 8 } - await expect( - Promise.resolve(callback!({ requestId: 'rekey-a', type: 'rekeyPage', page: PAGE, nextPage })) - ).resolves.toEqual({ type: 'rekeyed' }) - await expect( - Promise.resolve(callback!({ requestId: 'retire-a', type: 'retirePage', page: PAGE })) - ).resolves.toEqual({ type: 'retired' }) - expect(registry.mountPage).toHaveBeenCalledWith(PAGE) - expect(registry.rekeyPage).toHaveBeenCalledWith(PAGE, nextPage) - expect(registry.retirePage).toHaveBeenCalledWith(PAGE) - expect(installation.getMemoryProfile().retainedPageCount).toBe(1) - - installation.dispose() - installation.dispose() - expect(unsubscribe).toHaveBeenCalledOnce() - expect(registry.dispose).toHaveBeenCalledOnce() - }) - - it('returns only stable renderer failure codes', async () => { - let callback: RequestCallback | null = null - const registry = { - dispose: vi.fn(), - getMemoryProfile: vi.fn(), - mountPage: vi.fn(async () => { - throw new Error('browser_client_page_renderer_attach_timeout') - }), - rekeyPage: vi.fn(), - retirePage: vi.fn(() => { - throw new Error('sensitive renderer detail') - }) - } - installBrowserClientPageRenderer({ - registry, - subscribe: (next) => { - callback = next - return () => {} - } - }) - - await expect( - Promise.resolve(callback!({ requestId: 'mount-a', type: 'mountPage', page: PAGE })) - ).resolves.toEqual({ type: 'failed', errorCode: 'browser_client_page_renderer_attach_timeout' }) - await expect( - Promise.resolve(callback!({ requestId: 'retire-a', type: 'retirePage', page: PAGE })) - ).resolves.toEqual({ - type: 'failed', - errorCode: 'browser_client_page_renderer_operation_failed' - }) - }) -}) diff --git a/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx b/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx index a62cf5705b6..26fb3fd733f 100644 --- a/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx +++ b/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx @@ -303,7 +303,6 @@ describe('AgentTerminalPreview', () => { await waitFor(() => expect(imeHarness.forwarders).toHaveLength(1)) }) - // Assert the forwarder receives live snapshot-seeded flags; replay ordering is covered in preview-terminal-snapshot-replay.test.ts. it('hands the forwarder the live mirror seeded from the snapshot flags', async () => { platformState.value = 'darwin' connect.mockResolvedValue({ diff --git a/src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts b/src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts deleted file mode 100644 index 4b70f62962c..00000000000 --- a/src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { TerminalKittyKeyboardModeTracker } from '../../../../shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker' -import type { - TerminalPreviewReplayChunk, - TerminalPreviewSnapshot -} from '../../../../shared/terminal/replay/terminal-preview' -import { replayPreviewConnectionSnapshot } from './preview-terminal-snapshot-replay' - -function apply( - snapshot: Partial, - replay: TerminalPreviewReplayChunk[] = [], - kittyKeyboardModes = new TerminalKittyKeyboardModeTracker() -): { modes: TerminalKittyKeyboardModeTracker; written: string[] } { - const written: string[] = [] - replayPreviewConnectionSnapshot({ - snapshot: { data: '', cols: 80, rows: 24, ...snapshot }, - replay, - kittyKeyboardModes, - write: (chunk, live) => { - written.push(chunk) - if (live) { - kittyKeyboardModes.scan(chunk) - } else { - kittyKeyboardModes.scanReplay(chunk) - } - } - }) - return { modes: kittyKeyboardModes, written } -} - -// Snapshot ANSI omits kitty pushes; restore proven metadata in order before the IME forwarder reads it. -describe('replayPreviewConnectionSnapshot', () => { - it('replaces an earlier 8 when a replacement snapshot proves 0', () => { - const modes = new TerminalKittyKeyboardModeTracker() - apply({ kittyKeyboardFlags: 8 }, [], modes) - apply({ kittyKeyboardFlags: 0 }, [], modes) - expect(modes.flags).toBe(0) - expect(modes.snapshotFlags).toBe(0) - }) - - it('carries live-proven flags across a resync snapshot that proves nothing', () => { - // Old hosts omit kitty metadata; retain live-proven flags so resync cannot downgrade an active CSI-u TUI. - const modes = new TerminalKittyKeyboardModeTracker() - apply({ data: 'first frame' }, [], modes) - modes.scan('\x1b[>8u') - apply({ data: 'second frame' }, [], modes) - expect(modes.flags).toBe(8) - expect(modes.snapshotFlags).toBe(8) - }) - - it('restores onto the screen the snapshot scan selected', () => { - const { modes } = apply({ data: '\x1b[?1049h', kittyKeyboardFlags: 8 }) - expect(modes.isAlternateScreen).toBe(true) - expect(modes.snapshotFlags).toBe(8) - // Leaving the alternate screen returns to the main screen's own slot, which - // this snapshot never proved. - modes.scan('\x1b[?1049l') - expect(modes.snapshotFlags).toBeUndefined() - }) - - it('advances a proven suffix with live semantics and applies redelivery idempotently', () => { - const { modes } = apply({ kittyKeyboardFlags: 0 }, [ - { data: '\x1b[>8u', mode: 'live' }, - // Redelivered pushes must not leave stale stack frames after the app’s single pop. - { data: '\x1b[>8u', mode: 'replay' } - ]) - expect(modes.flags).toBe(8) - modes.scan('\x1b[ ({ useAgentRowConversationName: () => null })) -vi.mock('../sidebar/workspace-card/activity/CacheTimer', () => ({ - default: () => null, - usePromptCacheCountdownForPane: () => null -})) - -afterEach(async () => { - cleanup() - await vi.dynamicImportSettled() -}) - -const agent: AgentRow = { - paneKey: 'tab:leaf', - agentType: 'claude', - state: 'working', - startedAt: 60000, - entry: { - paneKey: 'tab:leaf', - state: 'working', - prompt: 'Review the change', - updatedAt: 60000, - stateStartedAt: 60000, - stateHistory: [] - }, - tab: { - id: 'tab', - ptyId: null, - worktreeId: 'workspace', - title: 'Agent', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } -} - -describe('agent child disclosure', () => { - it('toggles children without activating the surrounding agent or workspace', () => { - const activate = vi.fn() - const toggle = vi.fn() - const pointerDown = vi.fn() - const keyDown = vi.fn() - render( -
- -
- ) - const button = screen.getByRole('button', { name: 'Show 2 child agents' }) - fireEvent.pointerDown(button) - fireEvent.keyDown(button, { key: 'Enter' }) - fireEvent.keyDown(button, { key: ' ' }) - fireEvent.click(button) - expect(toggle).toHaveBeenCalledTimes(1) - expect(activate).not.toHaveBeenCalled() - expect(pointerDown).not.toHaveBeenCalled() - expect(keyDown).not.toHaveBeenCalled() - }) -}) - -describe.each(['compact', 'full'] as const)('%s row disclosure actions', (mode) => { - it.each([undefined, 'eligible'] as const)( - 'keeps child expansion separate from row actions in %s send mode', - (sendTargetStatus) => { - const onActivate = vi.fn(), - onSendTargetClick = vi.fn(), - onDismiss = vi.fn(), - onToggleChildAgents = vi.fn() - const props = { - agent, - now: 120000, - childAgentCount: 2, - childAgentsExpanded: false, - onToggleChildAgents, - onActivate, - sendTargetStatus, - onSendTargetClick - } - render( - - {mode === 'compact' ? ( - - ) : ( - - )} - - ) - fireEvent.click(screen.getByRole('button', { name: 'Show 2 child agents' })) - expect(onToggleChildAgents).toHaveBeenCalledTimes(1) - expect(onActivate).not.toHaveBeenCalled() - expect(onSendTargetClick).not.toHaveBeenCalled() - expect(onDismiss).not.toHaveBeenCalled() - fireEvent.click(screen.getByText('Review the change')) - if (sendTargetStatus) { - expect(onSendTargetClick).toHaveBeenCalledWith(agent.paneKey) - expect(onActivate).not.toHaveBeenCalled() - } else { - expect(onActivate).toHaveBeenCalledWith(agent.tab.id, agent.paneKey) - if (mode === 'full') { - fireEvent.click(screen.getByRole('button', { name: 'Dismiss agent' })) - expect(onDismiss).toHaveBeenCalledWith(agent.paneKey) - expect(onActivate).toHaveBeenCalledTimes(1) - } - } - } - ) -}) diff --git a/src/renderer/src/components/dashboard/agent-row-pane-live-title.test.ts b/src/renderer/src/components/dashboard/agent-row-pane-live-title.test.ts deleted file mode 100644 index ecaa74be60d..00000000000 --- a/src/renderer/src/components/dashboard/agent-row-pane-live-title.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { TerminalLayoutSnapshot } from '../../../../shared/workspace-layout/terminal-tab-types' -import { resolveAgentRowPaneLiveTitle } from './agent-row-pane-live-title' - -const LEAF_A = '11111111-1111-4111-8111-111111111111' -const LEAF_B = '22222222-2222-4222-8222-222222222222' -const LEAF_C = '33333333-3333-4333-8333-333333333333' - -const SPLIT: TerminalLayoutSnapshot = { - root: { - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', leafId: LEAF_A }, - second: { type: 'leaf', leafId: LEAF_B } - }, - activeLeafId: LEAF_A, - expandedLeafId: null -} - -describe('resolveAgentRowPaneLiveTitle', () => { - it('returns undefined for a single-pane tab, where the tab title is the pane title', () => { - const single: TerminalLayoutSnapshot = { - root: { type: 'leaf', leafId: LEAF_A }, - activeLeafId: LEAF_A, - expandedLeafId: null - } - expect(resolveAgentRowPaneLiveTitle(single, { 1: '✳ Redis cache' }, LEAF_A)).toBeUndefined() - expect(resolveAgentRowPaneLiveTitle(undefined, { 1: '✳ Redis cache' }, LEAF_A)).toBeUndefined() - }) - - it('gives each leaf of a split its own runtime pane title', () => { - const titles = { 1: '✳ Linear work log', 2: '✳ Redis cache strategy' } - expect(resolveAgentRowPaneLiveTitle(SPLIT, titles, LEAF_A)).toBe('✳ Linear work log') - expect(resolveAgentRowPaneLiveTitle(SPLIT, titles, LEAF_B)).toBe('✳ Redis cache strategy') - }) - - it('returns null rather than a sibling title when the pane has no slot', () => { - expect(resolveAgentRowPaneLiveTitle(SPLIT, { 1: '✳ Linear work log' }, LEAF_B)).toBeNull() - expect(resolveAgentRowPaneLiveTitle(SPLIT, undefined, LEAF_A)).toBeNull() - // A leaf that is not in this layout must never inherit a pane title. - expect(resolveAgentRowPaneLiveTitle(SPLIT, { 1: 'a', 2: 'b' }, LEAF_C)).toBeNull() - // An unparseable paneKey yields no leaf id, which must suppress, not guess. - expect(resolveAgentRowPaneLiveTitle(SPLIT, { 1: 'a', 2: 'b' }, undefined)).toBeNull() - }) - - it('walks replay creation order, not tree order, for a nested split', () => { - // Left pane split again: tree order is [A, C, B], creation order is [A, B, C]. - const nested: TerminalLayoutSnapshot = { - root: { - type: 'split', - direction: 'horizontal', - first: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: LEAF_A }, - second: { type: 'leaf', leafId: LEAF_C } - }, - second: { type: 'leaf', leafId: LEAF_B } - }, - activeLeafId: LEAF_A, - expandedLeafId: null - } - const titles = { 1: 'first', 2: 'second', 3: 'third' } - expect(resolveAgentRowPaneLiveTitle(nested, titles, LEAF_A)).toBe('first') - expect(resolveAgentRowPaneLiveTitle(nested, titles, LEAF_B)).toBe('second') - expect(resolveAgentRowPaneLiveTitle(nested, titles, LEAF_C)).toBe('third') - }) -}) diff --git a/src/renderer/src/components/dashboard/dashboard-worktree-launch-options.test.ts b/src/renderer/src/components/dashboard/dashboard-worktree-launch-options.test.ts deleted file mode 100644 index 31fab64219b..00000000000 --- a/src/renderer/src/components/dashboard/dashboard-worktree-launch-options.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - DASHBOARD_MAX_LAUNCH_WORKTREES, - type DashboardCard -} from '../../../../shared/dashboard-snapshot' - -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 { buildDashboardWorktreeLaunchOptions } from './dashboard-worktree-launch-options' - -type LaunchState = Parameters[0] - -function state(overrides: Partial = {}): LaunchState { - return { - repos: [], - worktreesByRepo: {}, - folderWorkspaces: [], - projectGroups: [], - detectedAgentIds: [], - remoteDetectedAgentIds: {}, - runtimeDetectedAgentIds: {}, - settings: null, - ...overrides - } -} - -function card(overrides: Partial = {}): DashboardCard { - return { - paneKey: 'pane-1', - ptyId: 'pty-1', - agentType: 'codex', - bucket: 'working', - dotState: 'working', - task: 'Ship it', - repoId: 'repo-1', - worktreeId: 'worktree-1', - tabId: 'tab-1', - leafId: 'leaf-1', - repoName: 'Orca', - worktreeName: 'Dashboard', - startedAt: 1, - finishedAt: null, - stateChangedAt: 1, - unseen: false, - ...overrides - } -} - -describe('buildDashboardWorktreeLaunchOptions', () => { - it('stops at the bound the snapshot validator enforces', () => { - const cards = Array.from({ length: DASHBOARD_MAX_LAUNCH_WORKTREES + 25 }, (_unused, index) => - card({ paneKey: `pane-${index}`, worktreeId: `worktree-${index}` }) - ) - - const options = buildDashboardWorktreeLaunchOptions( - state({ detectedAgentIds: ['codex'] }), - cards - ) - - expect(Object.keys(options)).toHaveLength(DASHBOARD_MAX_LAUNCH_WORKTREES) - }) - - it('uses each git workspace execution host instead of local detection', () => { - const options = buildDashboardWorktreeLaunchOptions( - state({ - repos: [ - { - id: 'repo-ssh', - path: '/repo-ssh', - displayName: 'repo-ssh', - badgeColor: 'blue', - addedAt: 1, - connectionId: 'ssh-1' - }, - { - id: 'repo-runtime', - path: '/repo-runtime', - displayName: 'repo-runtime', - badgeColor: 'blue', - addedAt: 1, - executionHostId: 'runtime:hub-1' - } - ] as LaunchState['repos'], - worktreesByRepo: { - 'repo-ssh': [{ id: 'ssh-worktree', repoId: 'repo-ssh' }], - 'repo-runtime': [{ id: 'runtime-worktree', repoId: 'repo-runtime' }] - } as unknown as LaunchState['worktreesByRepo'], - detectedAgentIds: ['claude'], - remoteDetectedAgentIds: { 'ssh-1': ['grok'] }, - runtimeDetectedAgentIds: { 'hub-1': ['aider'] } - }), - [ - card({ repoId: 'repo-ssh', worktreeId: 'ssh-worktree', agentType: 'grok' }), - card({ repoId: 'repo-runtime', worktreeId: 'runtime-worktree', agentType: 'aider' }) - ] - ) - - expect(options).toEqual({ 'ssh-worktree': ['grok'], 'runtime-worktree': ['aider'] }) - }) - - it('resolves folder workspace detection through its project host', () => { - const worktreeId = folderWorkspaceKey('folder-1') - const options = buildDashboardWorktreeLaunchOptions( - state({ - folderWorkspaces: [ - { - id: 'folder-1', - projectGroupId: 'group-1', - connectionId: 'ssh-folder' - } as FolderWorkspace - ], - projectGroups: [{ id: 'group-1' } as ProjectGroup], - remoteDetectedAgentIds: { 'ssh-folder': ['goose'] } - }), - [card({ repoId: 'folder-workspace:group-1', worktreeId })] - ) - - expect(options).toEqual({ [worktreeId]: ['codex', 'goose'] }) - }) -}) diff --git a/src/renderer/src/components/editor/autosave/editor-autosave-holds.test.ts b/src/renderer/src/components/editor/autosave/editor-autosave-holds.test.ts deleted file mode 100644 index 2ba0ce44c74..00000000000 --- a/src/renderer/src/components/editor/autosave/editor-autosave-holds.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { createEditorStore } from './editor-autosave-controller-test-fixture' -import { editorFileHoldKey, pathMutationHoldKeys } from './editor-autosave-holds' - -// Emulate a Windows client to ensure its path rules cannot fold distinct POSIX host paths. -vi.mock('@/lib/desktop-window-chrome', async (importOriginal) => ({ - ...(await importOriginal()), - isLocalWindowsDesktopClient: () => true -})) - -function tab(id: string, filePath: string, patch: Partial = {}): OpenFile { - return { - id, - filePath, - relativePath: filePath.split(/[\\/]/).pop() ?? filePath, - worktreeId: 'wt-other', - language: 'typescript', - isDirty: true, - mode: 'edit', - ...patch - } -} - -describe('discard hold keys on a Windows client', () => { - const state = createEditorStore().getState() - const remote = { runtimeEnvironmentId: 'env-1' } - - it('keeps a POSIX backslash file apart from the slash path', () => { - const backslash = tab('a', '/repo/a\\b.ts', remote) - const slash = tab('b', '/repo/a/b.ts', remote) - expect([editorFileHoldKey(state, backslash), editorFileHoldKey(state, slash)]).not.toContain( - 'a' - ) - expect(editorFileHoldKey(state, backslash)).not.toBe(editorFileHoldKey(state, slash)) - const discarded = pathMutationHoldKeys(state, { - worktreeId: 'wt-1', - worktreePath: '/repo', - relativePath: 'a/b.ts', - ...remote - }) - expect(discarded.has(editorFileHoldKey(state, slash))).toBe(true) - expect(discarded.has(editorFileHoldKey(state, backslash))).toBe(false) - }) - - it('still matches one file across an edit tab and an unstaged diff tab', () => { - const editTab = tab('a', '/repo/a/b.ts', remote) - const diffTab = tab('b', '/repo/a/b.ts', { ...remote, mode: 'diff', diffSource: 'unstaged' }) - expect(editorFileHoldKey(state, editTab)).toBe(editorFileHoldKey(state, diffTab)) - }) - - it('folds separators and drive case for a local Windows path', () => { - const local = { worktreeId: 'wt-1' } - const key = editorFileHoldKey(state, tab('a', 'C:\\repo\\a.ts', local)) - expect(key).not.toBe('a') - expect(key).toBe(editorFileHoldKey(state, tab('b', 'c:/repo/a.ts', local))) - }) - - it('holds a `\\\\wsl.localhost` tab while its file is discarded via `\\\\wsl$`', () => { - const local = { worktreeId: 'wt-1' } - const tabKey = editorFileHoldKey( - state, - tab('b', '\\\\wsl.localhost\\ubuntu\\repo\\a.ts', local) - ) - const discarded = pathMutationHoldKeys(state, { - worktreeId: 'wt-1', - worktreePath: '\\\\wsl$\\Ubuntu\\repo', - relativePath: 'a.ts' - }) - expect(tabKey).not.toBe('b') - expect(discarded.has(tabKey)).toBe(true) - // Keep Linux path case and distinguish WSL aliases from a real share named wsl. - expect( - discarded.has(editorFileHoldKey(state, tab('c', '\\\\wsl$\\Ubuntu\\repo\\A.ts', local))) - ).toBe(false) - expect( - discarded.has(editorFileHoldKey(state, tab('d', '\\\\wsl\\Ubuntu\\repo\\a.ts', local))) - ).toBe(false) - }) -}) diff --git a/src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree-collapsed-work.test.tsx b/src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree-collapsed-work.test.tsx deleted file mode 100644 index a547aefb4c8..00000000000 --- a/src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree-collapsed-work.test.tsx +++ /dev/null @@ -1,98 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { GitBranchChangeEntry } from '../../../../../../shared/git/diff/git-diff-compare-types' - -vi.mock('@/store', () => ({ - useAppStore: (selector: (state: Record) => unknown) => - selector({ combinedDiffFileTreeWidth: 420, setCombinedDiffFileTreeWidth: () => {} }) -})) - -const { CombinedDiffFileTree } = await import('./combined-diff-file-tree') - -class NoopResizeObserver implements ResizeObserver { - observe(): void {} - unobserve(): void {} - disconnect(): void {} -} - -let host: HTMLDivElement -let root: Root - -beforeEach(() => { - globalThis.IS_REACT_ACT_ENVIRONMENT = true - host = document.createElement('div') - document.body.appendChild(host) - root = createRoot(host) - vi.stubGlobal('ResizeObserver', NoopResizeObserver) -}) - -afterEach(() => { - act(() => root.unmount()) - host.remove() - vi.unstubAllGlobals() - vi.restoreAllMocks() -}) - -/** Count path reads as a deterministic proxy for tree construction work. */ -function countingEntries(count: number): { - entries: GitBranchChangeEntry[] - reads: () => number -} { - let reads = 0 - const entries = Array.from({ length: count }, (_, index) => { - const path = `src/dir${index % 5}/file-${index}.ts` - const entry = { status: 'modified' } as GitBranchChangeEntry - Object.defineProperty(entry, 'path', { - configurable: true, - enumerable: true, - get: () => { - reads += 1 - return path - } - }) - return entry - }) - return { entries, reads: () => reads } -} - -function renderTree(entries: GitBranchChangeEntry[], collapsed: boolean): void { - act(() => { - root.render( - {}} - onNavigate={() => {}} - /> - ) - }) -} - -describe('CombinedDiffFileTree while collapsed', () => { - it('does not filter, build or flatten the tree behind a collapsed panel', () => { - const { entries, reads } = countingEntries(300) - - renderTree(entries, true) - - expect(host.childElementCount).toBe(0) - expect(reads()).toBe(0) - }) - - it('builds the same tree as soon as it is expanded', () => { - const { entries, reads } = countingEntries(300) - - renderTree(entries, true) - renderTree(entries, false) - - expect(reads()).toBeGreaterThanOrEqual(entries.length) - expect(host.textContent).toContain('Files') - }) -}) diff --git a/src/renderer/src/components/editor/combined-diff/browse-files/use-combined-diff-tree-navigation.test.ts b/src/renderer/src/components/editor/combined-diff/browse-files/use-combined-diff-tree-navigation.test.ts deleted file mode 100644 index 26d4ecec282..00000000000 --- a/src/renderer/src/components/editor/combined-diff/browse-files/use-combined-diff-tree-navigation.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -// @vitest-environment happy-dom - -import React from 'react' -import { renderHook } from '@testing-library/react' -import { describe, expect, it, vi } from 'vitest' -import type { DiffSection } from '../../diff/sections/diff-section-types' -import { useCombinedDiffTreeNavigation } from './use-combined-diff-tree-navigation' - -function makeSection(key: string, viewed: boolean): DiffSection { - return { - key, - path: key, - status: 'modified', - originalContent: '', - modifiedContent: '', - collapsed: false, - loading: !viewed, - loadOnDemand: !viewed, - dirty: false, - diffResult: null, - largeDiffRenderLimit: null - } -} - -function renderNavigation(sections: DiffSection[], entrySignature: string) { - const sectionsRef = { current: sections } as React.RefObject - return renderHook( - (props: { sections: DiffSection[]; entrySignature: string }) => { - sectionsRef.current = props.sections - return useCombinedDiffTreeNavigation({ - ensureSectionLoaded: vi.fn(), - entrySignature: props.entrySignature, - markDirectScrollInput: vi.fn(), - scrollToIndex: vi.fn(), - sectionIndexByKey: new Map(props.sections.map((section, index) => [section.key, index])), - sections: props.sections, - sectionsRef, - toggleSection: vi.fn(), - treeMode: 'all' - }) - }, - { initialProps: { sections, entrySignature } } - ) -} - -describe('useCombinedDiffTreeNavigation viewedSectionKeys', () => { - it('keeps every viewed key when sections are reordered under one entry signature', () => { - const a = makeSection('a', true) - const b = makeSection('b', true) - const view = renderNavigation([a, b], 'sig') - expect([...view.result.current.viewedSectionKeys].sort()).toEqual(['a', 'b']) - - view.rerender({ sections: [b, a], entrySignature: 'sig' }) - expect([...view.result.current.viewedSectionKeys].sort()).toEqual(['a', 'b']) - }) - - it('patches only the flipped section while keys stay in place', () => { - const a = makeSection('a', true) - const view = renderNavigation([a, makeSection('b', false)], 'sig') - expect([...view.result.current.viewedSectionKeys]).toEqual(['a']) - - view.rerender({ sections: [a, makeSection('b', true)], entrySignature: 'sig' }) - expect([...view.result.current.viewedSectionKeys].sort()).toEqual(['a', 'b']) - }) - - it('reuses the cached set when no section changed viewed state', () => { - const sections = [makeSection('a', true), makeSection('b', false)] - const view = renderNavigation(sections, 'sig') - const first = view.result.current.viewedSectionKeys - - view.rerender({ sections: [...sections], entrySignature: 'sig' }) - expect(view.result.current.viewedSectionKeys).toBe(first) - }) -}) diff --git a/src/renderer/src/components/editor/diff/monaco-view/diff-editor-word-wrap-options.test.ts b/src/renderer/src/components/editor/diff/monaco-view/diff-editor-word-wrap-options.test.ts deleted file mode 100644 index 2d80a1621e4..00000000000 --- a/src/renderer/src/components/editor/diff/monaco-view/diff-editor-word-wrap-options.test.ts +++ /dev/null @@ -1,104 +0,0 @@ -// @vitest-environment happy-dom -import { describe, expect, it, vi } from 'vitest' -import type { editor } from 'monaco-editor' -import { syncDiffEditorOriginalWordWrap } from './diff-editor-word-wrap-options' - -describe('syncDiffEditorOriginalWordWrap', () => { - function fakeEditor() { - const listeners = new Set<() => void>() - let options: editor.IEditorOptions = {} - const editorStub = { - updateOptions: vi.fn((next: editor.IEditorOptions) => { - options = { ...options, ...next } - }), - getRawOptions: () => options, - onDidChangeConfiguration: (listener: () => void) => { - listeners.add(listener) - return { - dispose: () => { - listeners.delete(listener) - } - } - }, - emitDidChangeConfiguration: () => { - listeners.forEach((listener) => listener()) - } - } - return editorStub - } - - function monacoDiffHost(sideBySide: boolean): HTMLElement { - const host = document.createElement('div') - const widget = document.createElement('div') - widget.classList.add('monaco-diff-editor') - widget.classList.toggle('side-by-side', sideBySide) - host.append(widget) - return host - } - - function fakeDiffEditor(root = monacoDiffHost(true)): { - diffEditor: Parameters[0] - original: ReturnType - modified: ReturnType - } { - const original = fakeEditor() - const modified = fakeEditor() - return { - original, - modified, - diffEditor: { - getOriginalEditor: () => original, - getModifiedEditor: () => modified, - getContainerDomNode: () => root - } - } - } - - it('reapplies the original pane wrap after Monaco clears it, and stops after dispose', async () => { - const root = monacoDiffHost(true) - expect(root.classList.contains('side-by-side')).toBe(false) - const { diffEditor, original } = fakeDiffEditor(root) - const disposable = syncDiffEditorOriginalWordWrap(diffEditor, true) - original.updateOptions.mockClear() - - original.updateOptions({ wordWrapOverride2: 'off' }) - original.emitDidChangeConfiguration() - await Promise.resolve() - - expect(original.getRawOptions().wordWrapOverride2).toBe('inherit') - - original.updateOptions.mockClear() - disposable.dispose() - original.updateOptions({ wordWrapOverride2: 'off' }) - original.emitDidChangeConfiguration() - await Promise.resolve() - - expect(original.getRawOptions().wordWrapOverride2).toBe('off') - expect(original.updateOptions).toHaveBeenCalledTimes(1) - }) - - it('observes the settled layout after an inline-to-side-by-side transition', async () => { - const host = monacoDiffHost(false) - const { diffEditor, original, modified } = fakeDiffEditor(host) - const disposable = syncDiffEditorOriginalWordWrap(diffEditor, true) - - original.emitDidChangeConfiguration() - modified.emitDidChangeConfiguration() - host.querySelector('.monaco-diff-editor')?.classList.add('side-by-side') - await Promise.resolve() - - expect(original.getRawOptions().wordWrapOverride2).toBe('inherit') - disposable.dispose() - }) - - it('cancels a queued update when the editor is disposed', async () => { - const { diffEditor, original } = fakeDiffEditor() - const disposable = syncDiffEditorOriginalWordWrap(diffEditor, true) - original.updateOptions({ wordWrapOverride2: 'off' }) - original.emitDidChangeConfiguration() - disposable.dispose() - await Promise.resolve() - - expect(original.getRawOptions().wordWrapOverride2).toBe('off') - }) -}) diff --git a/src/renderer/src/components/editor/diff/monaco-view/diff-model-swap-view-state.test.ts b/src/renderer/src/components/editor/diff/monaco-view/diff-model-swap-view-state.test.ts deleted file mode 100644 index 4185ab9aa35..00000000000 --- a/src/renderer/src/components/editor/diff/monaco-view/diff-model-swap-view-state.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -// @vitest-environment happy-dom -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { editor } from 'monaco-editor' -import { preserveDiffViewStateAcrossModelSwaps } from './diff-model-swap-view-state' - -type ModelListener = () => void - -function modelEditorFixture() { - let willChangeListener: ModelListener = () => {} - let didChangeListener: ModelListener = () => {} - const disposeWillChange = vi.fn() - const disposeDidChange = vi.fn() - return { - editor: { - onWillChangeModel: (listener: ModelListener) => { - willChangeListener = listener - return { dispose: disposeWillChange } - }, - onDidChangeModel: (listener: ModelListener) => { - didChangeListener = listener - return { dispose: disposeDidChange } - } - } as unknown as editor.ICodeEditor, - fireWillChange: () => willChangeListener(), - fireDidChange: () => didChangeListener(), - disposeWillChange, - disposeDidChange - } -} - -describe('diff model swap view state', () => { - beforeEach(() => { - vi.restoreAllMocks() - }) - - it('coalesces a two-sided model rotation into one view-state restore', () => { - const original = modelEditorFixture() - const modified = modelEditorFixture() - const viewState = { original: {}, modified: {} } as editor.IDiffEditorViewState - const diffEditor = { - getOriginalEditor: () => original.editor, - getModifiedEditor: () => modified.editor, - getModel: () => ({ original: {}, modified: {} }), - saveViewState: vi.fn(() => viewState), - restoreViewState: vi.fn() - } as unknown as editor.IStandaloneDiffEditor - const scheduledFrames: FrameRequestCallback[] = [] - vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => { - scheduledFrames.push(callback) - return scheduledFrames.length - }) - vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {}) - - preserveDiffViewStateAcrossModelSwaps(diffEditor) - original.fireWillChange() - original.fireDidChange() - modified.fireWillChange() - modified.fireDidChange() - - expect(diffEditor.saveViewState).toHaveBeenCalledOnce() - expect(window.cancelAnimationFrame).toHaveBeenCalledWith(1) - scheduledFrames[1](0) - expect(diffEditor.restoreViewState).toHaveBeenCalledOnce() - expect(diffEditor.restoreViewState).toHaveBeenCalledWith(viewState) - }) - - it('cancels pending work and listeners when the editor is disposed', () => { - const original = modelEditorFixture() - const modified = modelEditorFixture() - const diffEditor = { - getOriginalEditor: () => original.editor, - getModifiedEditor: () => modified.editor, - saveViewState: () => ({ original: {}, modified: {} }), - restoreViewState: vi.fn() - } as unknown as editor.IStandaloneDiffEditor - vi.spyOn(window, 'requestAnimationFrame').mockReturnValue(7) - vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {}) - const subscription = preserveDiffViewStateAcrossModelSwaps(diffEditor) - - modified.fireWillChange() - modified.fireDidChange() - subscription.dispose() - - expect(window.cancelAnimationFrame).toHaveBeenCalledWith(7) - expect(original.disposeWillChange).toHaveBeenCalledOnce() - expect(original.disposeDidChange).toHaveBeenCalledOnce() - expect(modified.disposeWillChange).toHaveBeenCalledOnce() - expect(modified.disposeDidChange).toHaveBeenCalledOnce() - }) -}) diff --git a/src/renderer/src/components/editor/diff/monaco-view/diff-monaco-model-disposal.test.ts b/src/renderer/src/components/editor/diff/monaco-view/diff-monaco-model-disposal.test.ts deleted file mode 100644 index e70e9e6f4d5..00000000000 --- a/src/renderer/src/components/editor/diff/monaco-view/diff-monaco-model-disposal.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - disposeUnattachedMonacoModelsByPathPrefixes, - getDiffViewerMonacoModelPathPrefixes, - getDiffViewerMonacoModelPaths -} from './diff-monaco-model-disposal' - -type FakeModel = { - dispose: () => void - isAttachedToEditor: () => boolean - uri: { toString: (skipEncoding?: boolean) => string } -} - -function createRegistry(models: Map) { - return { - Uri: { - parse: (value: string) => value - }, - editor: { - getModel: (uri: unknown) => models.get(String(uri)) ?? null, - getModels: () => [...models.values()] - } - } -} - -function createModel( - modelPath: string, - attached: boolean, - dispose: () => void = () => {}, - decodedModelPath: string = modelPath -): FakeModel { - return { - dispose, - isAttachedToEditor: () => attached, - uri: { - toString: (skipEncoding?: boolean) => (skipEncoding ? decodedModelPath : modelPath) - } - } -} - -describe('diff Monaco model disposal', () => { - it('disposes generated tab models by owned path prefix', () => { - const baseDispose = vi.fn() - const generatedDispose = vi.fn() - const siblingDispose = vi.fn() - const attachedDispose = vi.fn() - const ownedPaths = getDiffViewerMonacoModelPaths({ modelKey: 'tab-1', generationSuffix: '' }) - const generatedPaths = getDiffViewerMonacoModelPaths({ - modelKey: 'tab-1', - generationSuffix: ':large-diff-generation:2' - }) - const attachedGeneratedPaths = getDiffViewerMonacoModelPaths({ - modelKey: 'tab-1', - generationSuffix: ':large-diff-generation:3' - }) - const siblingPaths = getDiffViewerMonacoModelPaths({ modelKey: 'tab-10', generationSuffix: '' }) - const models = new Map([ - [ownedPaths.originalModelPath, createModel(ownedPaths.originalModelPath, false, baseDispose)], - [ - generatedPaths.originalModelPath, - createModel(generatedPaths.originalModelPath, false, generatedDispose) - ], - [ - siblingPaths.originalModelPath, - createModel(siblingPaths.originalModelPath, false, siblingDispose) - ], - [ - attachedGeneratedPaths.originalModelPath, - createModel(attachedGeneratedPaths.originalModelPath, true, attachedDispose) - ] - ]) - const monacoRegistry = createRegistry(models) - const { originalModelPathPrefix } = getDiffViewerMonacoModelPathPrefixes('tab-1') - - disposeUnattachedMonacoModelsByPathPrefixes(monacoRegistry, [originalModelPathPrefix]) - - expect(baseDispose).toHaveBeenCalledOnce() - expect(generatedDispose).toHaveBeenCalledOnce() - expect(siblingDispose).not.toHaveBeenCalled() - expect(attachedDispose).not.toHaveBeenCalled() - }) - - it('does not dispose colon-suffixed sibling tab models by prefix', () => { - const ownedDispose = vi.fn() - const siblingDispose = vi.fn() - const ownedPaths = getDiffViewerMonacoModelPaths({ - modelKey: 'foo', - originalModelKey: 'foo:bar', - generationSuffix: '' - }) - const siblingPaths = getDiffViewerMonacoModelPaths({ - modelKey: 'foo:bar', - generationSuffix: '' - }) - const models = new Map([ - [ - ownedPaths.originalModelPath, - createModel(ownedPaths.originalModelPath, false, ownedDispose, ownedPaths.originalModelPath) - ], - [ - siblingPaths.originalModelPath, - createModel( - siblingPaths.originalModelPath, - false, - siblingDispose, - siblingPaths.originalModelPath - ) - ] - ]) - const monacoRegistry = createRegistry(models) - const { originalModelPathPrefix } = getDiffViewerMonacoModelPathPrefixes('foo') - - disposeUnattachedMonacoModelsByPathPrefixes(monacoRegistry, [originalModelPathPrefix]) - - expect(ownedDispose).toHaveBeenCalledOnce() - expect(siblingDispose).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/editor/diff/review/diff-navigation-context.test.tsx b/src/renderer/src/components/editor/diff/review/diff-navigation-context.test.tsx deleted file mode 100644 index 4f07ca779f7..00000000000 --- a/src/renderer/src/components/editor/diff/review/diff-navigation-context.test.tsx +++ /dev/null @@ -1,144 +0,0 @@ -// @vitest-environment happy-dom -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { editor } from 'monaco-editor' -import { - DiffNavigationProvider, - useDiffEditorRegistration, - useDiffNavigation, - type DiffEditorRegistrationContextValue, - type DiffNavigationContextValue -} from './diff-navigation-context' - -type FakeDiffEditor = editor.IStandaloneDiffEditor & { - setLineChanges: (count: number) => void - fireUpdate: () => void - goToDiff: ReturnType - disposeUpdate: ReturnType - containerNode: HTMLElement -} - -function createFakeEditor(initialCount: number): FakeDiffEditor { - let count = initialCount - let updateCallback: (() => void) | null = null - const disposeUpdate = vi.fn(() => { - updateCallback = null - }) - const containerNode = document.createElement('div') - const editor = { - getLineChanges: () => (count > 0 ? Array.from({ length: count }, () => ({})) : []), - goToDiff: vi.fn(), - getContainerDomNode: () => containerNode, - onDidUpdateDiff: (cb: () => void) => { - updateCallback = cb - return { - dispose: disposeUpdate - } - }, - setLineChanges: (next: number) => { - count = next - }, - fireUpdate: () => updateCallback?.(), - disposeUpdate, - containerNode - } as unknown as FakeDiffEditor - return editor -} - -let captured: DiffNavigationContextValue | null = null -let registration: DiffEditorRegistrationContextValue | null = null -let registrationRenderCount = 0 - -function Probe(): null { - captured = useDiffNavigation() - return null -} - -function RegistrationProbe(): null { - registration = useDiffEditorRegistration() - registrationRenderCount += 1 - return null -} - -describe('DiffNavigationProvider', () => { - let container: HTMLDivElement | null = null - let root: Root | null = null - - function mount(): void { - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - act(() => { - root?.render( - - - - - ) - }) - } - - afterEach(() => { - if (root) { - act(() => root?.unmount()) - } - container?.remove() - container = null - root = null - captured = null - registration = null - registrationRenderCount = 0 - }) - - it('re-renders when onDidUpdateDiff flips the count 0 -> N (count is state)', () => { - mount() - const editor = createFakeEditor(0) - act(() => registration?.registerDiffEditor(editor)) - expect(captured?.changeCount).toBe(0) - - act(() => { - editor.setLineChanges(2) - editor.fireUpdate() - }) - expect(captured?.changeCount).toBe(2) - expect(registrationRenderCount).toBe(1) - }) - - it('ignores a stale unregister for an editor that is no longer current (identity guard)', () => { - mount() - const oldEditor = createFakeEditor(1) - const newEditor = createFakeEditor(4) - - // Fast-swap: new editor registers before the old one's dispose fires. - act(() => registration?.registerDiffEditor(oldEditor)) - act(() => registration?.registerDiffEditor(newEditor)) - expect(captured?.changeCount).toBe(4) - expect(oldEditor.disposeUpdate).toHaveBeenCalledOnce() - - // Replacing registration must dispose the old subscription so stale updates cannot restore its count. - act(() => { - oldEditor.setLineChanges(9) - oldEditor.fireUpdate() - }) - expect(captured?.changeCount).toBe(4) - - act(() => registration?.unregisterDiffEditor(oldEditor)) - - expect(captured?.changeCount).toBe(4) - act(() => captured?.goToNextDiff()) - expect(newEditor.goToDiff).toHaveBeenCalledWith('next') - expect(oldEditor.goToDiff).not.toHaveBeenCalled() - }) - - it('disposes the active diff update subscription when the provider unmounts', () => { - mount() - const editor = createFakeEditor(1) - act(() => registration?.registerDiffEditor(editor)) - - act(() => root?.unmount()) - - expect(editor.disposeUpdate).toHaveBeenCalledOnce() - root = null - }) -}) diff --git a/src/renderer/src/components/editor/editor-untitled-dont-save-dialogs.test.tsx b/src/renderer/src/components/editor/editor-untitled-dont-save-dialogs.test.tsx deleted file mode 100644 index 2b47c1f9fac..00000000000 --- a/src/renderer/src/components/editor/editor-untitled-dont-save-dialogs.test.tsx +++ /dev/null @@ -1,103 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, renderHook } from '@testing-library/react' -import type { StoreApi } from 'zustand/vanilla' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AppState } from '@/store' -import { - createFakeEditorDisk, - createUntitledNoteStore, - type FakeEditorDisk -} from './autosave/editor-autosave-controller-test-fixture' -import { getDiskBaselineSignature } from '../../../../shared/disk-baseline-signature' -import { useTerminalSaveDialog } from '../terminal/useTerminalSaveDialog' -import { - useTerminalEditorCloseDialogActions, - type TerminalEditorCloseDialogActionsInput -} from '../use-terminal-editor-close-dialog-actions' - -const storeHolder = vi.hoisted((): { store: StoreApi | null } => ({ store: null })) - -function requireStore(): StoreApi { - if (!storeHolder.store) { - throw new Error('test store not initialised') - } - return storeHolder.store -} - -vi.mock('@/store', () => ({ useAppStore: { getState: () => requireStore().getState() } })) -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: vi.fn() })) - -const FILE_ID = '/repo/untitled.md' - -function mainWindowDialogController(fileId: string): TerminalEditorCloseDialogActionsInput { - const pendingEditorCloseQueueRef = { current: [fileId] } - return { - advanceEditorCloseQueue: vi.fn(), - closedReactionsRef: { current: new Map() }, - inFlightSaveFileIdRef: { current: null }, - isClosingRef: { current: false }, - pendingEditorCloseQueueRef, - queueEditorCloseRequests: vi.fn(), - releaseCloseDialogGuardAfterDebounce: vi.fn(), - saveDialogFileId: fileId, - setSaveDialogFileId: vi.fn(), - settleQueuedClose: vi.fn((settled: string) => { - pendingEditorCloseQueueRef.current = pendingEditorCloseQueueRef.current.filter( - (queued) => queued !== settled - ) - }), - waitForFileClosed: vi.fn(async () => true), - windowCloseAfterDirtyRef: { current: null } - } -} - -describe("Don't Save in the unsaved-changes dialogs on a never-saved untitled note", () => { - let disk: FakeEditorDisk - let store: StoreApi - - beforeEach(() => { - disk = createFakeEditorDisk({ [FILE_ID]: '' }) - Object.assign(window, { api: { fs: disk.fs } }) - store = createUntitledNoteStore('untitled.md') - storeHolder.store = store - store.getState().setLastKnownDiskSignature(FILE_ID, getDiskBaselineSignature('')) - store.getState().setEditorDraft(FILE_ID, 'typed but never saved') - store.getState().markFileDirty(FILE_ID, true) - }) - - afterEach(() => { - cleanup() - Reflect.deleteProperty(window, 'api') - storeHolder.store = null - }) - - it('main window removes the empty placeholder', async () => { - const { result } = renderHook(() => - useTerminalEditorCloseDialogActions(mainWindowDialogController(FILE_ID)) - ) - - await act(() => result.current.handleSaveDialogDiscard()) - - expect(store.getState().openFiles).toHaveLength(0) - await vi.waitFor(() => expect(disk.files.has(FILE_ID)).toBe(false)) - }) - - it('floating panel removes the empty placeholder', async () => { - const { result } = renderHook(() => - useTerminalSaveDialog({ - openFiles: store.getState().openFiles, - closeFile: store.getState().closeFile - }) - ) - act(() => result.current.requestCloseFile(FILE_ID)) - expect(result.current.saveDialogFileId).toBe(FILE_ID) - - await act(async () => { - // Why: the hook's result type declares the discard handler as void though it returns a promise. - await Promise.resolve(result.current.handleSaveDialogDiscard()) - }) - - expect(store.getState().openFiles).toHaveLength(0) - await vi.waitFor(() => expect(disk.files.has(FILE_ID)).toBe(false)) - }) -}) diff --git a/src/renderer/src/components/editor/external-changes/editor-clean-tab-draft-invariant.test.ts b/src/renderer/src/components/editor/external-changes/editor-clean-tab-draft-invariant.test.ts index 5091d453f99..46244b09840 100644 --- a/src/renderer/src/components/editor/external-changes/editor-clean-tab-draft-invariant.test.ts +++ b/src/renderer/src/components/editor/external-changes/editor-clean-tab-draft-invariant.test.ts @@ -1,10 +1,8 @@ // Clean tabs must not retain disk-text drafts that could later overwrite a shared model. import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { attachEditorAutosaveController } from '../autosave/editor-autosave-controller' -import { requestEditorFileSave } from '../autosave/editor-autosave' + import { __clearSelfWriteRegistryForTests } from './editor-self-write-registry' import { createEditorStore } from '../autosave/editor-autosave-controller-test-fixture' -import { reloadTabContentFromDisk } from './ExternalFileChangeBanner' import { stampCleanTabDiskBaseline } from './editor-clean-tab-disk-baseline' import { getDiskBaselineSignature } from '../../../../../shared/disk-baseline-signature' @@ -33,14 +31,6 @@ function openCleanTab(disk: string, language = 'typescript') { return { store, id } } -function expectNoCleanDraft(store: ReturnType): void { - for (const tab of store.getState().openFiles) { - if (!tab.isDirty) { - expect(store.getState().editorDrafts[tab.id]).toBeUndefined() - } - } -} - beforeEach(() => { vi.useFakeTimers() stubGuardedDisk({ [GUARDED_PATH]: 'disk' }) @@ -52,27 +42,6 @@ afterEach(() => { __clearSelfWriteRegistryForTests() }) -it('save completion leaves no draft on the now-clean tab', async () => { - const { store, id } = openCleanTab('disk') - store.getState().setEditorDraft(id, 'saved text') - store.getState().markFileDirty(id, true) - const cleanup = attachEditorAutosaveController(store) - try { - await requestEditorFileSave({ fileId: id }) - expectNoCleanDraft(store) - } finally { - cleanup() - } -}) - -it('reload leaves no draft', () => { - const { store, id } = openCleanTab('disk') - store.getState().setEditorDraft(id, 'mine') - store.getState().markFileDirty(id, true) - reloadTabContentFromDisk(store.getState().openFiles[0], vi.fn()) - expectNoCleanDraft(store) -}) - it("a reload keeps a clean Markdown tab's trailing-whitespace draft, but not one over older text", () => { const { store, id } = openCleanTab('# notes', 'markdown') store.getState().setEditorDraft(id, '# notes\n\n') diff --git a/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.recheck.test.ts b/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.recheck.test.ts index 90fa30eddf2..8864a70bf6e 100644 --- a/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.recheck.test.ts +++ b/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.recheck.test.ts @@ -21,10 +21,7 @@ vi.mock('@/lib/file-owner-runtime-target', () => { }) import { createTestStore } from '@/store/slices/store-test-helpers' -import { - attachRestoredTabConflictScan, - MAX_VERIFY_ATTEMPTS -} from './editor-restored-tab-conflict-scan' +import { attachRestoredTabConflictScan } from './editor-restored-tab-conflict-scan' import { getDiskBaselineSignature } from '../../../../../shared/disk-baseline-signature' const FILE = '/repo/a.ts' @@ -71,14 +68,3 @@ it('marks a dirty runtime-owned tab deleted when its host says the file is gone' ) expect(tab().externalMutation).toBe('deleted') }) - -it('stops retrying without a banner when the disk can never be checked', async () => { - mocks.readRuntimeFileContent.mockRejectedValue(new Error('host unreachable')) - mocks.runtimePathsExist.mockResolvedValue([{ error: 'unverifiable' }]) - detach = attachRestoredTabConflictScan(store) - await vi.advanceTimersByTimeAsync(10 * 60_000) - - expect(mocks.readRuntimeFileContent).toHaveBeenCalledTimes(MAX_VERIFY_ATTEMPTS) - // Why no banner: the guarded save refuses newer disk on its own. - expect(tab().externalMutation).toBeUndefined() -}) diff --git a/src/renderer/src/components/editor/markdown-preview/document-worker/markdown-preview-document-search-scope.test.ts b/src/renderer/src/components/editor/markdown-preview/document-worker/markdown-preview-document-search-scope.test.ts deleted file mode 100644 index 8b36d6bf1f2..00000000000 --- a/src/renderer/src/components/editor/markdown-preview/document-worker/markdown-preview-document-search-scope.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -// @vitest-environment happy-dom -import { describe, expect, it, vi } from 'vitest' -import { MarkdownPreviewDocumentEngine } from './markdown-preview-document-engine' -import { - applyMarkdownPreviewSearchHighlights, - clearMarkdownPreviewSearchHighlights, - setActiveMarkdownPreviewSearchMatch -} from '../search/markdown-preview-search' - -describe('virtual preview document search scope', () => { - it('keeps worker occurrences aligned with document text around saved notes and copy labels', async () => { - const engine = new MarkdownPreviewDocumentEngine() - engine.load('> First needle.\n>\n> Second needle.') - const result = await engine.search('needle') - const body = document.createElement('div') - body.innerHTML = `
-

First needle.

-
Saved note quoting needle.
- -
needle
-

Second needle.

-
` - const instance = {} - const ranges = applyMarkdownPreviewSearchHighlights(instance, body, 'needle', { - documentOnly: true - }) - expect(result?.matches).toEqual([ - { block: 0, occurrence: 0 }, - { block: 0, occurrence: 1 } - ]) - expect(ranges.map((range) => range.startContainer.textContent)).toEqual([ - 'First needle.', - 'Second needle.' - ]) - const scroll = vi.spyOn(body.querySelector('p')!, 'scrollIntoView') - setActiveMarkdownPreviewSearchMatch(instance, ranges, 0, { scrollIntoView: false }) - expect(scroll).not.toHaveBeenCalled() - setActiveMarkdownPreviewSearchMatch(instance, ranges, 0) - expect(scroll).toHaveBeenCalledOnce() - clearMarkdownPreviewSearchHighlights(instance) - }) - - it('maps matches across syntax spans without expanding offscreen code', async () => { - const engine = new MarkdownPreviewDocumentEngine() - engine.load('```javascript\nconst needle = 42\n```') - const result = await engine.search('const needle') - const body = document.createElement('div') - body.innerHTML = - '
const needle = 42\n
' - const instance = {} - const ranges = applyMarkdownPreviewSearchHighlights(instance, body, 'const needle', { - documentOnly: true - }) - expect(result?.matches).toEqual([{ block: 0, occurrence: 0 }]) - expect(ranges.map((range) => range.toString())).toEqual(['const needle']) - expect( - applyMarkdownPreviewSearchHighlights(instance, body, 'needle = 42', { - documentOnly: true - }).map((range) => range.toString()) - ).toEqual(['needle = 42']) - clearMarkdownPreviewSearchHighlights(instance) - }) - - it('uses the same outer code group for nested raw HTML code', async () => { - const engine = new MarkdownPreviewDocumentEngine() - engine.load('needle suffix') - const body = document.createElement('div') - body.innerHTML = 'needle suffix' - const instance = {} - const ranges = applyMarkdownPreviewSearchHighlights(instance, body, 'needle suffix', { - documentOnly: true - }) - expect((await engine.search('needle suffix'))?.matches).toEqual([{ block: 0, occurrence: 0 }]) - expect(ranges.map((range) => range.toString())).toEqual(['needle suffix']) - clearMarkdownPreviewSearchHighlights(instance) - }) -}) diff --git a/src/renderer/src/components/editor/markdown-source-tools/monaco/monaco-markdown-doc-link-decorations.test.ts b/src/renderer/src/components/editor/markdown-source-tools/monaco/monaco-markdown-doc-link-decorations.test.ts index 14a35c36f5a..cf040c536c6 100644 --- a/src/renderer/src/components/editor/markdown-source-tools/monaco/monaco-markdown-doc-link-decorations.test.ts +++ b/src/renderer/src/components/editor/markdown-source-tools/monaco/monaco-markdown-doc-link-decorations.test.ts @@ -1,10 +1,5 @@ -import type { editor } from 'monaco-editor' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - createMarkdownDocLinkDecorationController, - getMarkdownDocLinkDecorationRanges, - MARKDOWN_DOC_LINK_DECORATION_REFRESH_DELAY_MS -} from './monaco-markdown-doc-link-decorations' +import { describe, expect, it } from 'vitest' +import { getMarkdownDocLinkDecorationRanges } from './monaco-markdown-doc-link-decorations' describe('getMarkdownDocLinkDecorationRanges', () => { it('ignores doc links inside inline and fenced code', () => { @@ -19,107 +14,4 @@ describe('getMarkdownDocLinkDecorationRanges', () => { } ]) }) - - it('supports CRLF markdown without splitting the full document', () => { - const split = vi.spyOn(String.prototype, 'split') - - expect(getMarkdownDocLinkDecorationRanges('intro\r\n[[other.md]]\r\n')).toEqual([ - { - startLineNumber: 2, - startColumn: 1, - endLineNumber: 2, - endColumn: 13 - } - ]) - expect(split).not.toHaveBeenCalled() - }) -}) - -describe('createMarkdownDocLinkDecorationController', () => { - afterEach(() => { - vi.useRealTimers() - }) - - it('debounces full-model decoration rebuilds during rapid content changes', () => { - vi.useFakeTimers() - - let modelValue = '[[initial.md]]' - let contentListener = (): void => {} - const set = vi.fn() - const clear = vi.fn() - const dispose = vi.fn() - - const editorInstance = { - createDecorationsCollection: () => ({ set, clear }), - getModel: () => ({ getValue: () => modelValue }), - onDidChangeModelContent: (listener: () => void) => { - contentListener = listener - return { dispose } - } - } as unknown as editor.IStandaloneCodeEditor - - const controller = createMarkdownDocLinkDecorationController(editorInstance, () => 'markdown') - expect(set).toHaveBeenCalledTimes(1) - - set.mockClear() - modelValue = '[[first.md]]' - contentListener?.() - vi.advanceTimersByTime(MARKDOWN_DOC_LINK_DECORATION_REFRESH_DELAY_MS - 1) - modelValue = '[[second.md]]' - contentListener?.() - modelValue = '[[final.md]]' - contentListener?.() - - expect(set).not.toHaveBeenCalled() - vi.advanceTimersByTime(MARKDOWN_DOC_LINK_DECORATION_REFRESH_DELAY_MS - 1) - expect(set).not.toHaveBeenCalled() - - vi.advanceTimersByTime(1) - expect(set).toHaveBeenCalledTimes(1) - expect(set.mock.calls[0]?.[0]).toEqual([ - { - range: { - startLineNumber: 1, - startColumn: 1, - endLineNumber: 1, - endColumn: 13 - }, - options: { - inlineClassName: 'monaco-markdown-doc-link', - stickiness: 1 - } - } - ]) - - controller.dispose() - expect(dispose).toHaveBeenCalledTimes(1) - expect(clear).toHaveBeenCalledTimes(1) - }) - - it('cancels pending decoration rebuilds on dispose', () => { - vi.useFakeTimers() - - let contentListener = (): void => {} - const set = vi.fn() - const clear = vi.fn() - - const editorInstance = { - createDecorationsCollection: () => ({ set, clear }), - getModel: () => ({ getValue: () => '[[initial.md]]' }), - onDidChangeModelContent: (listener: () => void) => { - contentListener = listener - return { dispose: vi.fn() } - } - } as unknown as editor.IStandaloneCodeEditor - - const controller = createMarkdownDocLinkDecorationController(editorInstance, () => 'markdown') - set.mockClear() - - contentListener?.() - controller.dispose() - vi.advanceTimersByTime(MARKDOWN_DOC_LINK_DECORATION_REFRESH_DELAY_MS) - - expect(set).not.toHaveBeenCalled() - expect(clear).toHaveBeenCalledTimes(1) - }) }) diff --git a/src/renderer/src/components/editor/markdown/documents/use-markdown-document-watch-refresh.test.ts b/src/renderer/src/components/editor/markdown/documents/use-markdown-document-watch-refresh.test.ts deleted file mode 100644 index de09df20122..00000000000 --- a/src/renderer/src/components/editor/markdown/documents/use-markdown-document-watch-refresh.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -// @vitest-environment happy-dom -import { act, createElement } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { FsChangeEvent } from '../../../../../../shared/filesystem-entry-types' -import { ORCA_WORKTREE_FILE_CHANGE_EVENT } from '@/hooks/worktree-file-change-event' -import { useMarkdownDocumentWatchRefresh } from './use-markdown-document-watch-refresh' - -let root: Root -let container: HTMLDivElement - -function Harness({ - refresh -}: { - refresh: (requireFresh: boolean, freshAfter: number) => Promise -}): null { - useMarkdownDocumentWatchRefresh({ - enabled: true, - worktreePath: '/repo', - runtimeEnvironmentId: null, - refresh - }) - return null -} - -function change(events: FsChangeEvent[]): void { - window.dispatchEvent( - new CustomEvent(ORCA_WORKTREE_FILE_CHANGE_EVENT, { - detail: { runtimeEnvironmentId: null, payload: { worktreePath: '/repo', events } } - }) - ) -} - -async function advance(ms: number): Promise { - await act(async () => { - await vi.advanceTimersByTimeAsync(ms) - }) -} - -beforeEach(() => { - vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true) - vi.useFakeTimers() - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) -}) -afterEach(() => { - act(() => root.unmount()) - container.remove() - vi.useRealTimers() - vi.unstubAllGlobals() -}) - -describe('useMarkdownDocumentWatchRefresh', () => { - it('keeps one slow scan in flight and follows up once it settles', async () => { - let inFlight = 0 - let maxInFlight = 0 - const refresh = vi.fn( - () => - new Promise((resolve) => { - inFlight++ - maxInFlight = Math.max(maxInFlight, inFlight) - setTimeout(() => { - inFlight-- - resolve() - }, 1000) - }) - ) - await act(async () => root.render(createElement(Harness, { refresh }))) - // Watch batches arrive every 100 ms under sustained writes; each scan takes 1 s. - for (let i = 0; i < 30; i++) { - change([{ kind: 'create', absolutePath: `/repo/n${i}.md` }]) - await advance(100) - } - await advance(2000) - expect(maxInFlight).toBe(1) - // One scan per settled scan plus the trailing follow-up, not one per batch. - expect(refresh.mock.calls.length).toBeGreaterThanOrEqual(2) - expect(refresh.mock.calls.length).toBeLessThanOrEqual(4) - }) - - it('recovers from a scan that never settles', async () => { - const refresh = vi - .fn<(requireFresh: boolean, freshAfter: number) => Promise>() - .mockImplementationOnce(() => new Promise(() => {})) - .mockResolvedValue(undefined) - await act(async () => root.render(createElement(Harness, { refresh }))) - // Local and UNC listings have no timeout; later changes must not stay frozen behind one. - for (let i = 0; i < 20; i++) { - change([{ kind: 'create', absolutePath: `/repo/h${i}.md` }]) - await advance(5_000) - } - expect(refresh.mock.calls.length).toBeGreaterThanOrEqual(2) - }) -}) diff --git a/src/renderer/src/components/editor/markdown/link-routing/markdown-internal-links.test.ts b/src/renderer/src/components/editor/markdown/link-routing/markdown-internal-links.test.ts deleted file mode 100644 index 813cc98d9f4..00000000000 --- a/src/renderer/src/components/editor/markdown/link-routing/markdown-internal-links.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { resolveMarkdownLinkTarget } from './markdown-internal-links' - -// Path containment follows the runner platform’s case rules; fixtures avoid case differences for portability. - -const SOURCE = '/repo/docs/note.md' -const ROOT = '/repo' - -describe('resolveMarkdownLinkTarget', () => { - it('classifies relative .md inside a UNC worktree as markdown', () => { - const r = resolveMarkdownLinkTarget( - './guide.md', - '\\\\server\\share\\repo\\docs\\note.md', - '\\\\server\\share\\repo' - ) - expect(r).toEqual({ - kind: 'markdown', - absolutePath: '//server/share/repo/docs/guide.md', - relativePath: 'docs/guide.md' - }) - }) - - it('extracts hash line anchors from Windows drive-letter absolute .md links', () => { - const r = resolveMarkdownLinkTarget( - 'C:\\repo\\docs\\guide.md#L10', - 'C:\\repo\\docs\\note.md', - 'C:\\repo' - ) - expect(r).toMatchObject({ - kind: 'markdown', - absolutePath: 'C:/repo/docs/guide.md', - relativePath: 'docs/guide.md', - line: 10 - }) - }) - - it('extracts line+col from non-markdown file links', () => { - const r = resolveMarkdownLinkTarget('../src/PdfViewer.tsx:142:7', SOURCE, ROOT) - expect(r).toMatchObject({ - kind: 'file', - absolutePath: '/repo/src/PdfViewer.tsx', - relativePath: 'src/PdfViewer.tsx', - line: 142, - column: 7 - }) - }) - - it('does not treat :note in a filename as a line anchor', () => { - const r = resolveMarkdownLinkTarget('./my:note.md', SOURCE, ROOT) - expect(r).toMatchObject({ kind: 'markdown', line: undefined }) - expect((r as { absolutePath: string }).absolutePath).toContain('my:note.md') - }) - - it('does not treat a mid-name colon with digits as a line anchor', () => { - const r = resolveMarkdownLinkTarget('./weird:12name.md', SOURCE, ROOT) - expect(r).toMatchObject({ kind: 'markdown', line: undefined }) - }) - - it('classifies explicit UNC file URLs without losing the server name', () => { - const r = resolveMarkdownLinkTarget( - 'file://server/share/repo/docs/image.png', - '\\\\server\\share\\repo\\docs\\note.md', - '\\\\server\\share\\repo' - ) - expect(r).toMatchObject({ - kind: 'file', - uri: 'file://server/share/repo/docs/image.png', - absolutePath: '//server/share/repo/docs/image.png', - relativePath: 'docs/image.png' - }) - }) - - it('classifies explicit file URLs outside the worktree without a relative path', () => { - const r = resolveMarkdownLinkTarget('file:///tmp/image.png', SOURCE, ROOT) - expect(r).toMatchObject({ - kind: 'file', - uri: 'file:///tmp/image.png', - absolutePath: '/tmp/image.png', - relativePath: undefined - }) - }) - - it('never returns markdown when worktreeRoot is null', () => { - const r = resolveMarkdownLinkTarget('./guide.md', SOURCE, null) - expect(r?.kind).toBe('file') - }) - - it('returns null for malformed percent-encoded file URL paths', () => { - expect(resolveMarkdownLinkTarget('file:///repo/docs/%zz.md', SOURCE, ROOT)).toBeNull() - }) -}) diff --git a/src/renderer/src/components/editor/markdown/navigation/markdown-table-of-contents.test.ts b/src/renderer/src/components/editor/markdown/navigation/markdown-table-of-contents.test.ts deleted file mode 100644 index ed92bb4981d..00000000000 --- a/src/renderer/src/components/editor/markdown/navigation/markdown-table-of-contents.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { buildMarkdownTableOfContents } from './markdown-table-of-contents' - -afterEach(() => { - vi.restoreAllMocks() -}) - -describe('markdown table of contents', () => { - it('builds a nested h1-h5 outline', () => { - const toc = buildMarkdownTableOfContents( - '# Intro\n\n## Setup\n\n### Install\n\n#### Configure\n\n##### Options\n\n## Usage' - ) - - expect(toc).toEqual([ - { - id: 'intro', - level: 1, - title: 'Intro', - children: [ - { - id: 'setup', - level: 2, - title: 'Setup', - children: [ - { - id: 'install', - level: 3, - title: 'Install', - children: [ - { - id: 'configure', - level: 4, - title: 'Configure', - children: [ - { - id: 'options', - level: 5, - title: 'Options', - children: [] - } - ] - } - ] - } - ] - }, - { - id: 'usage', - level: 2, - title: 'Usage', - children: [] - } - ] - } - ]) - }) - - it('skips front matter and unsupported heading depths', () => { - const toc = buildMarkdownTableOfContents('---\ntitle: Doc\n---\n# Visible\n###### Hidden') - - expect(toc.map((item) => item.title)).toEqual(['Visible']) - }) - - it('skips headings inside fenced code blocks', () => { - const toc = buildMarkdownTableOfContents('# Install\n\n```sh\n# not a heading\n```\n\n## Real') - - expect(toc[0].children.map((item) => item.title)).toEqual(['Real']) - }) - - it('includes rendered markdown heading forms', () => { - const toc = buildMarkdownTableOfContents( - '# Intro\n\n ## Indented\n\nSetext *Title*\n---\n\n### https://example.com' - ) - - expect(toc[0].children).toEqual([ - { - id: 'indented', - level: 2, - title: 'Indented', - children: [] - }, - { - id: 'setext-title', - level: 2, - title: 'Setext Title', - children: [ - { - id: 'httpsexamplecom', - level: 3, - title: 'https://example.com', - children: [] - } - ] - } - ]) - }) - - it('extracts emphasized headings next to Korean text', () => { - const toc = buildMarkdownTableOfContents('# **"이런"**것은 강조됩니다') - - expect(toc[0]).toMatchObject({ - id: '이런것은-강조됩니다', - title: '"이런"것은 강조됩니다' - }) - }) - - it('uses GitHub-compatible duplicate slugs', () => { - const toc = buildMarkdownTableOfContents('# Repeat\n# Repeat') - - expect(toc.map((item) => item.id)).toEqual(['repeat', 'repeat-1']) - }) - - it('decodes HTML entities before slugging headings', () => { - const toc = buildMarkdownTableOfContents('# A & B') - - expect(toc[0]).toMatchObject({ - id: 'a--b', - title: 'A & B' - }) - }) -}) diff --git a/src/renderer/src/components/editor/markdown/source-scanning/markdown-reference-link-normalization.test.ts b/src/renderer/src/components/editor/markdown/source-scanning/markdown-reference-link-normalization.test.ts index 16929a46761..ae7740ec630 100644 --- a/src/renderer/src/components/editor/markdown/source-scanning/markdown-reference-link-normalization.test.ts +++ b/src/renderer/src/components/editor/markdown/source-scanning/markdown-reference-link-normalization.test.ts @@ -1,19 +1,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { marked } from 'marked' + import { normalizeMarkdownReferenceLinks } from './markdown-reference-link-normalization' // Use marked’s own fence ranges as an independent oracle for normalization boundaries. -function markedCodeRanges(markdown: string): [number, number][] { - const ranges: [number, number][] = [] - let offset = 0 - for (const token of marked.lexer(markdown.replace(/\r\n|\r/g, '\n'))) { - if (token.type === 'code') { - ranges.push([offset, offset + token.raw.length]) - } - offset += token.raw.length - } - return ranges -} afterEach(() => { vi.restoreAllMocks() @@ -28,61 +17,9 @@ describe('normalizeMarkdownReferenceLinks', () => { ).toBe('[Docs](https://example.com/docs)\n[Issue](https://example.com/issue "Issue")\n\n') }) - it('supports CRLF reference definitions', () => { - expect( - normalizeMarkdownReferenceLinks('[Docs]\r\n\r\n[docs]: https://example.com/docs\r\n') - ).toBe('[Docs](https://example.com/docs)\r\n\r\n') - }) - it('ignores definitions inside fenced code blocks', () => { const markdown = ['```md', '[docs]: https://example.com/docs', '```', '', '[Docs]'].join('\n') expect(normalizeMarkdownReferenceLinks(markdown)).toBe(markdown) }) - - it('never removes a definition marked keeps inside a fenced code block', () => { - const definition = '[docs]: https://example.com/docs' - const survivors: string[] = [] - for (const outer of ['```', '````', '~~~', '~~~~']) { - // Fence-shaped lines that do and do not close `outer`. - for (const inner of ['```', '````', '~~~', '````js', '``` ', '```` trailing', '~~~a`b']) { - const markdown = `${outer}\ncode\n${inner}\n${definition}\n[Docs]\n${outer}\n` - const offset = markdown.indexOf(definition) - const insideCode = markedCodeRanges(markdown).some( - ([start, end]) => offset >= start && offset < end - ) - if (insideCode && !normalizeMarkdownReferenceLinks(markdown).includes(definition)) { - survivors.push(markdown) - } - } - } - expect(survivors).toEqual([]) - }) - - it('scans newline-heavy documents without splitting into line arrays', () => { - const split = vi.spyOn(String.prototype, 'split') - const body = Array.from({ length: 5000 }, (_, index) => `line ${index + 1}`).join('\n') - const markdown = `${body}\n\n[Docs]\n\n[docs]: https://example.com/docs\n` - - const normalized = normalizeMarkdownReferenceLinks(markdown) - - expect(normalized).toContain('[Docs](https://example.com/docs)') - expect(split).not.toHaveBeenCalled() - }) - - it('folds whitespace-heavy reference labels without full whitespace replacement', () => { - const replace = vi.spyOn(String.prototype, 'replace') - const nonBreakingSpace = String.fromCharCode(160) - const labelParts = Array.from({ length: 300 }, (_, index) => `PastedLabel${index}`) - const usageLabel = labelParts.join(' ') - const definitionLabel = ` \t${labelParts.join(` \t ${nonBreakingSpace}`)}${nonBreakingSpace} ` - const markdown = `[Docs][${usageLabel}]\n\n[${definitionLabel}]: https://example.com/docs\n` - - expect(normalizeMarkdownReferenceLinks(markdown)).toBe('[Docs](https://example.com/docs)\n\n') - expect( - replace.mock.calls.filter( - ([pattern]) => pattern instanceof RegExp && pattern.source === '\\s+' - ) - ).toHaveLength(0) - }) }) diff --git a/src/renderer/src/components/editor/markdown/source-scanning/markdown-scanner-boundaries.test.ts b/src/renderer/src/components/editor/markdown/source-scanning/markdown-scanner-boundaries.test.ts index afb1d7f6c6a..9569f2fbc27 100644 --- a/src/renderer/src/components/editor/markdown/source-scanning/markdown-scanner-boundaries.test.ts +++ b/src/renderer/src/components/editor/markdown/source-scanning/markdown-scanner-boundaries.test.ts @@ -1,6 +1,5 @@ import { marked } from 'marked' -import { stripMarkdownCode } from './markdown-code-stripping' -import { getMarkdownFenceRanges } from './markdown-fence-scanner' + import { describe, expect, it } from 'vitest' import { markdownCodeSpanRanges, markdownFenceRanges } from './markdown-scan-ranges' import { createMarkdownCodeSpanScanner } from './markdown-code-span-scanner' @@ -28,23 +27,6 @@ it('does not expose inline spans inside fenced content', () => { expect(createMarkdownCodeSpanScanner(source).findSpanEnd(4)).toBeNull() }) -it.each(['\n', '\r\n', '\r'])('retains %j terminators while stripping code', (eol) => { - expect(stripMarkdownCode(['before', '`code`', 'after'].join(eol))).toBe( - ['before', '', 'after'].join(eol) - ) -}) - -it.each(['```~~~', '``` ~', '```\t', ' ```'])( - 'matches the parser on the closer %j', - (closer) => { - const source = `\`\`\`\ncode\n${closer}\n
after
\n` - const code = marked.lexer(source)[0] - expect(code.type).toBe('code') - expect(getMarkdownFenceRanges(source)).toEqual([[0, code.raw.length]]) - expect(stripMarkdownCode(source).includes('
after
')).toBe(closer === '```~~~') - } -) - it.each(['-', '--', '---'])('keeps multiline spans after a bare %s line', (divider) => { const source = `Text\n${divider}\nA \`code\nspan\` here` const spans: string[] = [] diff --git a/src/renderer/src/components/editor/model-lifetime/identity/editor-model-uri-language-service.test.ts b/src/renderer/src/components/editor/model-lifetime/identity/editor-model-uri-language-service.test.ts deleted file mode 100644 index 7d6fd2350fc..00000000000 --- a/src/renderer/src/components/editor/model-lifetime/identity/editor-model-uri-language-service.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -// The TypeScript worker uses model URIs as filenames, determining import isolation and TSX detection. -import { describe, expect, it } from 'vitest' -import { URI } from 'monaco-editor/esm/vs/base/common/uri.js' -import { TypeScriptWorker } from 'monaco-editor/esm/vs/language/typescript/tsWorker.js' -import { toEditorModelUri } from './editor-model-uri' - -function workerWith(files: Record) { - const mirrors = Object.entries(files).map(([uri, text]) => ({ - uri: URI.parse(uri), - version: 1, - getValue: () => text - })) - return new TypeScriptWorker( - { getMirrorModels: () => mirrors }, - { - // Monaco's defaults plus the JSX setting Orca applies in monaco-setup. - compilerOptions: { allowNonTsExtensions: true, target: 99, jsx: 1 }, - extraLibs: {}, - inlayHintsOptions: {} - } - ) -} - -describe('editor model URIs in the TypeScript language service', () => { - const hostA = '["hub-a","ssh:target"]' - const viewText = "import { value } from './value'\nexport const view =
{value}
\n" - - it("resolves an import to the open file on the same host, not another host's", async () => { - const view = toEditorModelUri('/repo/src/view.tsx', hostA) - const value = toEditorModelUri('/repo/src/value.ts', hostA) - const otherHostValue = toEditorModelUri('/repo/src/value.ts', '["hub-b","ssh:target"]') - const worker = workerWith({ - [view]: viewText, - [value]: 'export const value = 1\n', - [otherHostValue]: 'export const value = 2\n' - }) - - const definitions = await worker.getDefinitionAtPosition(view, viewText.indexOf('value')) - - expect(definitions?.map((definition) => definition.fileName)).toEqual([value]) - }) - - it('serves hover and definitions for a remote UNC file, apart from the same POSIX path', async () => { - const text = "import { value } from './value'\nvalue\n" - const view = toEditorModelUri('//server/share/src/view.ts', hostA) - const value = toEditorModelUri('//server/share/src/value.ts', hostA) - const worker = workerWith({ - [view]: text, - [value]: 'export const value = 1\n', - [toEditorModelUri('/server/share/src/value.ts', hostA)]: 'export const value = 2\n' - }) - const position = text.lastIndexOf('value') - - const definitions = await worker.getDefinitionAtPosition(view, position) - const hover = await worker.getQuickInfoAtPosition(view, position) - - expect(definitions?.map((definition) => definition.fileName)).toEqual([value]) - expect(hover?.displayParts?.map((part) => part.text).join('')).toContain('value: 1') - }) - - it.each([ - ['../value', '/repo/value.ts'], - ['../../../../../repo/src/value', '/repo/src/value.ts'], - ['../../../../../../value', '/value.ts'] - ])("keeps %s inside the owner's tree", async (specifier, sameHostPath) => { - const text = `import { value } from '${specifier}'\nvalue\n` - const view = toEditorModelUri('/repo/src/view.ts', hostA) - const sameHost = toEditorModelUri(sameHostPath, hostA) - const worker = workerWith({ - [view]: text, - [sameHost]: 'export const value = 1\n', - // Local files and another host's files at every path the import could climb to. - ...Object.fromEntries( - ['/repo/value.ts', '/repo/src/value.ts', '/value.ts'].flatMap((path) => [ - [toEditorModelUri(path), 'export const value = 2\n'], - [toEditorModelUri(path, '["hub-b","ssh:target"]'), 'export const value = 3\n'] - ]) - ) - }) - - const definitions = await worker.getDefinitionAtPosition(view, text.lastIndexOf('value')) - - expect(definitions?.map((definition) => definition.fileName)).toEqual([sameHost]) - }) -}) diff --git a/src/renderer/src/components/editor/model-lifetime/identity/editor-model-uri.test.ts b/src/renderer/src/components/editor/model-lifetime/identity/editor-model-uri.test.ts deleted file mode 100644 index 9187affd9f2..00000000000 --- a/src/renderer/src/components/editor/model-lifetime/identity/editor-model-uri.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { describe, expect, it } from 'vitest' -// The same module the public `monaco.Uri` re-exports, without loading the editor bundle. -import { URI } from 'monaco-editor/esm/vs/base/common/uri.js' -import { toEditorModelUri } from './editor-model-uri' - -const paths = [ - '/repo/src/a.ts', - 'C:/repo/src/a.ts', - 'C:\\repo\\src\\a.ts', - '\\\\server\\share\\a.ts', - '//server/share/a.ts', - 'file:///C:/repo/src/a.ts', - 'file:///repo/src/a.ts', - '/repo/src/a b.ts', - '/repo/src/a%20b.ts', - '/repo/src/a#b.ts', - '\\\\wsl$\\Ubuntu\\home\\a.ts' -] - -describe('toEditorModelUri', () => { - // Model creation parses path strings and registry lookup uses toString; require round-trip stability so disposal finds the created model. - it.each(paths)('round-trips through the Uri.parse the editor applies to %s', (path) => { - const modelUri = toEditorModelUri(path) - expect(URI.parse(modelUri).toString()).toBe(modelUri) - expect(toEditorModelUri(modelUri)).toBe(modelUri) - }) - - it('collapses the drive-letter casing Windows treats as one file', () => { - expect(toEditorModelUri('C:/repo/a.ts')).toBe(toEditorModelUri('c:/repo/a.ts')) - expect(toEditorModelUri('file:///C:/repo/a.ts')).toBe(toEditorModelUri('C:/repo/a.ts')) - }) - - it('keeps distinct POSIX paths distinct', () => { - expect(toEditorModelUri('/repo/a b.ts')).not.toBe(toEditorModelUri('/repo/a%20b.ts')) - }) - - it.each(paths)('keys an owner by authority and keeps the real path for %s', (path) => { - const local = URI.parse(toEditorModelUri(path)) - const remoteUri = toEditorModelUri(path, '["hub-a","ssh:target#1"]') - const remote = URI.parse(remoteUri) - expect(remote.scheme).toBe('vscode-remote') - // Move UNC servers into owned URI paths and tag authorities to retain their distinct identity. - expect(remote.authority).toMatch(local.authority ? /^[0-9a-f]{16}-unc$/ : /^[0-9a-f]{16}$/) - expect(remote.path).toBe(local.authority ? `/${local.authority}${local.path}` : local.path) - expect(remote.path).not.toMatch(/^\/\//) - expect(remote.fragment).toBe('') - expect(remote.toString()).toBe(remoteUri) - expect(toEditorModelUri(remoteUri)).toBe(remoteUri) - expect(toEditorModelUri(path, '["hub-b","ssh:target#1"]')).not.toBe(remoteUri) - expect(toEditorModelUri(remoteUri, '["hub-a","ssh:target#1"]')).toBe(remoteUri) - }) - - it('keeps a UNC path apart from the same POSIX path under one owner', () => { - const owner = '["hub-a","ssh:target"]' - expect(toEditorModelUri('//server/share/a.ts', owner)).not.toBe( - toEditorModelUri('/server/share/a.ts', owner) - ) - }) - - it('never collapses a real folder shaped like an owner', () => { - const owner = '["hub-a","ssh:target"]' - for (const realPath of ['/.orca-owner/0123456789abcdef/repo/a.ts', '/vscode-remote:/a.ts']) { - expect(toEditorModelUri(realPath, owner)).not.toBe(toEditorModelUri('/repo/a.ts', owner)) - expect(URI.parse(toEditorModelUri(realPath, owner)).path).toBe(realPath) - } - }) -}) diff --git a/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-paste-fallback.test.ts b/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-paste-fallback.test.ts index 81d339fcebd..5b0ce0eab10 100644 --- a/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-paste-fallback.test.ts +++ b/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-paste-fallback.test.ts @@ -80,36 +80,4 @@ describe('rich markdown source fallback paste', () => { editor.destroy() } }) - - it('keeps line breaks and active marks', () => { - const editor = createEditor() - try { - editor.commands.setTextSelection({ from: 8, to: 14 }) - editor.commands.setMark('italic') - const literal = 'first\nsecond' - const slice = oversizedCitationSlice(editor, literal) - const event = new ClipboardEvent('paste', { - clipboardData: new DataTransfer(), - cancelable: true - }) - - handleRichMarkdownPaste({ - editor, - event, - filePath: '/repo/note.md', - worktreeId: 'worktree-1', - slice, - view: editor.view - }) - - const pasted = editor.state.doc.firstChild?.child(1) - expect(pasted?.text).toBe( - `${literal}${'[1]'.repeat(RICH_MARKDOWN_SOURCE_OWNING_NODE_LIMIT + 1)}` - ) - expect(pasted?.marks.map((mark) => mark.type.name)).toEqual(['italic']) - editor.state.doc.check() - } finally { - editor.destroy() - } - }) }) diff --git a/src/renderer/src/components/editor/rich-markdown/doc-links/rich-markdown-commands.test.ts b/src/renderer/src/components/editor/rich-markdown/doc-links/rich-markdown-commands.test.ts deleted file mode 100644 index afdcedd2f49..00000000000 --- a/src/renderer/src/components/editor/rich-markdown/doc-links/rich-markdown-commands.test.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { Editor } from '@tiptap/core' -import { createRichMarkdownExtensions } from '../schema/rich-markdown-extensions' -import { createRichMarkdownEditorCodec } from '../document/rich-markdown-source-transport' -import { runSlashCommand } from '../commands/rich-markdown-slash-commands' -import { slashCommands } from '../commands/rich-markdown-slash-command-catalog' -import type { SlashCommandId } from '../commands/rich-markdown-slash-command-primitives' - -function createEditor(content = '/'): Editor { - return new Editor({ - element: null, - extensions: createRichMarkdownExtensions({ codec: createRichMarkdownEditorCodec() }), - content, - contentType: 'markdown' - }) -} - -function getCommand(id: SlashCommandId) { - const command = slashCommands.find((candidate) => candidate.id === id) - if (!command) { - throw new Error(`Missing slash command ${id}`) - } - return command -} - -function runCommand(id: SlashCommandId, content = '/'): Editor { - const editor = createEditor(content) - editor.commands.setTextSelection(content.length + 1) - runSlashCommand(editor, { from: 1, to: content.length + 1 }, getCommand(id)) - return editor -} - -describe('rich markdown slash commands', () => { - it('supports deep heading slash commands', () => { - const h4Editor = createEditor('Deep heading') - const h5Editor = createEditor('Nested heading') - - try { - getCommand('heading-4').run(h4Editor) - getCommand('heading-5').run(h5Editor) - - expect(h4Editor.getMarkdown()).toBe('#### Deep heading') - expect(h5Editor.getMarkdown()).toBe('##### Nested heading') - expect(getCommand('heading-4').aliases).toContain('h4') - expect(getCommand('heading-5').aliases).toContain('h5') - } finally { - h4Editor.destroy() - h5Editor.destroy() - } - }) - - it('inserts a durable markdown table', () => { - const editor = runCommand('table') - - try { - expect(editor.getMarkdown()).toContain('| | | |') - expect(editor.getMarkdown()).toContain('| --- | --- | --- |') - } finally { - editor.destroy() - } - }) - - it('inserts a mermaid fenced code block', () => { - const editor = runCommand('mermaid') - - try { - expect(editor.getMarkdown()).toBe('```mermaid\ngraph TD\n A[Start] --> B[End]\n```') - } finally { - editor.destroy() - } - }) - - it('inserts inline math as a rendered rich editor node', () => { - const editor = runCommand('inline-math') - - try { - expect(editor.getMarkdown()).toBe('$x$') - expect(editor.getJSON()).toMatchObject({ - content: [ - { - content: [ - { - type: 'inlineMath', - attrs: { latex: 'x' } - } - ] - } - ] - }) - } finally { - editor.destroy() - } - }) - - it('inserts display math as a rendered rich editor node', () => { - const editor = runCommand('math-block') - - try { - expect(editor.getMarkdown()).toBe('$$\nx\n$$') - expect(editor.getJSON()).toMatchObject({ - content: [ - { - type: 'blockMath', - attrs: { latex: 'x' } - } - ] - }) - } finally { - editor.destroy() - } - }) - - it('parses existing display math as a rendered rich editor node', () => { - const editor = createEditor('Before\n\n$$\nx + y\n$$\n\nAfter') - - try { - expect(editor.getJSON()).toMatchObject({ - content: [ - { type: 'paragraph' }, - { - type: 'blockMath', - attrs: { latex: 'x + y' } - }, - { type: 'paragraph' } - ] - }) - expect(editor.getMarkdown()).toBe('Before\n\n$$\nx + y\n$$\n\nAfter') - } finally { - editor.destroy() - } - }) -}) diff --git a/src/renderer/src/components/editor/rich-markdown/doc-links/rich-markdown-doc-link-resolution.test.ts b/src/renderer/src/components/editor/rich-markdown/doc-links/rich-markdown-doc-link-resolution.test.ts deleted file mode 100644 index 09d538e07db..00000000000 --- a/src/renderer/src/components/editor/rich-markdown/doc-links/rich-markdown-doc-link-resolution.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -// @vitest-environment happy-dom - -import { Editor } from '@tiptap/react' -import StarterKit from '@tiptap/starter-kit' -import { afterEach, describe, expect, it } from 'vitest' -import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types' -import { createMarkdownDocLink } from './rich-markdown-doc-link' -import { createRichMarkdownEditorCodec } from '../document/rich-markdown-source-transport' - -const editors: Editor[] = [] -const guide: MarkdownDocument = { - filePath: '/repo/Guide.md', - relativePath: 'Guide.md', - basename: 'Guide.md', - name: 'Guide' -} -function docLinkEditor(): Editor { - const editor = new Editor({ - extensions: [StarterKit, createMarkdownDocLink(createRichMarkdownEditorCodec().transport)], - content: { - type: 'doc', - content: [ - { - type: 'paragraph', - content: [{ type: 'markdownDocLink', attrs: { target: 'Guide', label: 'Read guide' } }] - } - ] - } - }) - editors.push(editor) - return editor -} -function updateDocuments(editor: Editor, documents: MarkdownDocument[]): void { - const storage = editor.storage.markdownDocLink - if (!storage) { - throw new Error('Missing document-link storage') - } - storage.documents = documents - editor.view.dispatch(editor.state.tr.setMeta('docLinksUpdated', true)) -} -afterEach(() => editors.splice(0).forEach((editor) => editor.destroy())) - -describe('rich document link metadata refresh', () => { - it('resolves an existing link after the document list arrives without editing the document', () => { - const editor = docLinkEditor() - const link = editor.view.dom.querySelector('[data-doc-link-target="Guide"]') - expect(link?.classList.contains('rich-markdown-doc-link--missing')).toBe(true) - const before = editor.state.doc - const selection = editor.state.selection - updateDocuments(editor, [guide]) - expect(link?.classList.contains('rich-markdown-doc-link--missing')).toBe(false) - expect(editor.state.doc).toBe(before) - expect(editor.state.selection.eq(selection)).toBe(true) - expect(link?.textContent).toBe('Read guide') - expect(editor.view.dom.querySelector('[data-doc-link-target="Guide"]')).toBe(link) - }) - - it('marks an existing resolved link missing after its document is removed', () => { - const editor = docLinkEditor() - updateDocuments(editor, [guide]) - // A changed node forces resolution on the baseline too, isolating the removal refresh. - editor.view.dispatch( - editor.state.tr.setNodeMarkup(1, undefined, { target: 'Guide', label: 'Open guide' }) - ) - const link = editor.view.dom.querySelector('[data-doc-link-target="Guide"]') - expect(link?.classList.contains('rich-markdown-doc-link--missing')).toBe(false) - const before = editor.state.doc - updateDocuments(editor, []) - expect(link?.classList.contains('rich-markdown-doc-link--missing')).toBe(true) - expect(editor.state.doc).toBe(before) - expect(link?.textContent).toBe('Open guide') - }) -}) diff --git a/src/renderer/src/components/editor/rich-markdown/document/rich-markdown-literal-serialization.test.ts b/src/renderer/src/components/editor/rich-markdown/document/rich-markdown-literal-serialization.test.ts deleted file mode 100644 index b18cc2994b8..00000000000 --- a/src/renderer/src/components/editor/rich-markdown/document/rich-markdown-literal-serialization.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { Editor, type JSONContent } from '@tiptap/core' -import StarterKit from '@tiptap/starter-kit' -import { describe, expect, it, vi } from 'vitest' -import { createIsolatedMarkdownExtensionForTests } from '../schema/isolated-markdown-extension-for-tests' - -function createEditor(content: JSONContent | string) { - return new Editor({ - element: null, - extensions: [StarterKit, createIsolatedMarkdownExtensionForTests()], - content, - ...(typeof content === 'string' ? { contentType: 'markdown' as const } : {}) - }) -} - -function paragraph(text: string): JSONContent { - return { type: 'paragraph', content: [{ type: 'text', text }] } -} - -function expectReopens(editor: Editor) { - const reopened = createEditor(editor.getMarkdown()) - try { - expect(reopened.getJSON()).toEqual(editor.getJSON()) - } finally { - reopened.destroy() - } -} - -describe('literal Markdown serialization', () => { - it.each(['[ref]: ./target.md', '[ref]: <./target.md> "Title"'])( - 'preserves literal references across blocks with definition %j', - (definition) => { - const editor = createEditor({ - type: 'doc', - content: [paragraph('[literal][ref] and [ref]'), paragraph(definition)] - }) - try { - expectReopens(editor) - } finally { - editor.destroy() - } - } - ) - - it('reuses unchanged blocks but revalidates edited syntax', () => { - const editor = createEditor({ - type: 'doc', - content: [paragraph('[literal]'), paragraph('[[]]')] - }) - const parse = vi.spyOn(editor.markdown!, 'parse') - try { - expect(editor.getMarkdown()).toBe('[literal]\n\n[[]]') - expect(parse).toHaveBeenCalledTimes(2) - editor.getMarkdown() - expect(parse).toHaveBeenCalledTimes(2) - editor.commands.insertContentAt(10, { type: 'text', text: '(./target.md)' }) - const saved = editor.getMarkdown() - expect(parse).toHaveBeenCalledTimes(3) - expect(saved).toContain('\\[literal\\]') - expectReopens(editor) - } finally { - parse.mockRestore() - editor.destroy() - } - }) - - it('preserves headings, marked text, and nested blocks', () => { - const editor = createEditor({ - type: 'doc', - content: [ - { type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: '[[]]' }] }, - { - type: 'paragraph', - content: [{ type: 'text', text: '[literal]', marks: [{ type: 'bold' }] }] - }, - { - type: 'bulletList', - content: [{ type: 'listItem', content: [paragraph('[literal](./a)')] }] - } - ] - }) - try { - expectReopens(editor) - } finally { - editor.destroy() - } - }) -}) diff --git a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-capacity.test.ts b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-capacity.test.ts deleted file mode 100644 index 5cb17468a76..00000000000 --- a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-capacity.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -// @vitest-environment happy-dom -import { Editor } from '@tiptap/core' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { createRichMarkdownExtensions } from '../schema/rich-markdown-extensions' -import { setRichMarkdownImageResolverContext } from './rich-markdown-image-context' -import { createRichMarkdownEditorCodec } from '../document/rich-markdown-source-transport' -import { - blobUrlCache, - resetLocalImageCacheState as resetLocalImageSrcStateForTests -} from '../../document-images/local-image-src-cache' -import { prewarmMarkdownPreviewLocalImages } from '../../markdown-preview/links/markdown-preview-local-images' -import '../../document-images/useLocalImageSrc' - -const editors: Editor[] = [] -const originalApi = Object.getOwnPropertyDescriptor(window, 'api') -const readFile = vi.fn(async () => ({ - content: - 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aXioAAAAASUVORK5CYII=', - isBinary: true, - mimeType: 'image/png' -})) -let nextUrl = 0 - -function mountImages(count: number) { - const host = document.createElement('div') - document.body.appendChild(host) - const editor = new Editor({ - element: host, - extensions: createRichMarkdownExtensions({ codec: createRichMarkdownEditorCodec() }), - content: Array.from({ length: count }, (_, index) => `![](image-${index}.png)`).join('\n\n'), - contentType: 'markdown' - }) - editors.push(editor) - setRichMarkdownImageResolverContext(editor, { filePath: '/repo/docs/readme.md' }) - return { editor, host } -} - -beforeEach(() => { - resetLocalImageSrcStateForTests() - readFile.mockClear() - nextUrl = 0 - Object.defineProperty(window, 'api', { value: { fs: { readFile } }, configurable: true }) - vi.spyOn(URL, 'createObjectURL').mockImplementation(() => `blob:capacity-${nextUrl++}`) - vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {}) -}) - -afterEach(() => { - for (const editor of editors.splice(0)) { - if (!editor.isDestroyed) { - editor.destroy() - } - } - resetLocalImageSrcStateForTests() - vi.restoreAllMocks() - if (originalApi) { - Object.defineProperty(window, 'api', originalApi) - } else { - Reflect.deleteProperty(window, 'api') - } - document.body.innerHTML = '' -}) - -it('displays every image in a 101-image document within the byte budget', async () => { - const view = mountImages(101) - await vi.waitFor(() => { - expect(view.host.querySelectorAll('img[src]')).toHaveLength(101) - }) - expect(readFile).toHaveBeenCalledTimes(101) - expect(blobUrlCache.size).toBe(101) - expect(URL.revokeObjectURL).not.toHaveBeenCalled() - const prewarm = prewarmMarkdownPreviewLocalImages('![](unleased.png)', '/repo/docs/readme.md') - await prewarm.done - expect(blobUrlCache.size).toBe(101) - expect(URL.revokeObjectURL).toHaveBeenCalledTimes(1) - view.editor.destroy() - expect(blobUrlCache.size).toBe(100) - expect(URL.revokeObjectURL).toHaveBeenCalledTimes(2) -}) - -it('keeps an entirely unleased prewarm within the entry target', async () => { - const prewarm = prewarmMarkdownPreviewLocalImages( - Array.from({ length: 101 }, (_, index) => `![](prewarm-${index}.png)`).join('\n\n'), - '/repo/docs/readme.md', - { limit: 101 } - ) - await prewarm.done - expect(readFile).toHaveBeenCalledTimes(101) - expect(blobUrlCache.size).toBe(100) - expect(URL.revokeObjectURL).toHaveBeenCalledTimes(1) -}) diff --git a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert-code-block.test.ts b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert-code-block.test.ts index 7e24fcf607a..1ee35014601 100644 --- a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert-code-block.test.ts +++ b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert-code-block.test.ts @@ -6,7 +6,6 @@ import { renderHook } from '@testing-library/react' import { createRichMarkdownExtensions } from '../schema/rich-markdown-extensions' import { createRichMarkdownEditorCodec } from '../document/rich-markdown-source-transport' import { useLocalImagePick } from './useLocalImagePick' -import { handleRichMarkdownImagePaste } from './rich-markdown-paste-image' vi.mock('@/runtime/runtime-file-import-client', () => ({ importExternalPathsToRuntime: vi.fn().mockResolvedValue({ @@ -100,20 +99,4 @@ describe('inserting an image while the cursor is inside a fenced code block', () expectFencedSplit(editor) }) - - it('keeps both halves fenced when a clipboard screenshot is pasted', async () => { - const handled = handleRichMarkdownImagePaste({ - editor: editor as never, - event: { - clipboardData: { items: [{ kind: 'file', type: 'image/png' }] }, - preventDefault: vi.fn() - } as unknown as ClipboardEvent, - filePath: '/repo/note.md', - worktreeId: 'wt-1' - }) - await flushPromises() - - expect(handled).toBe(true) - expectFencedSplit(editor) - }) }) diff --git a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-local-image.test.ts b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-local-image.test.ts index 7ccd6891db9..104316c1837 100644 --- a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-local-image.test.ts +++ b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-local-image.test.ts @@ -4,28 +4,11 @@ import { Editor } from '@tiptap/core' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createRichMarkdownExtensions } from '../schema/rich-markdown-extensions' import { createRichMarkdownEditorCodec } from '../document/rich-markdown-source-transport' -import { getLocalImageSrcCacheKey } from '../../document-images/useLocalImageSrc' -import { - releaseLocalImageBlob as releaseLocalImageSrcByKey, - resetLocalImageCacheState as resetLocalImageSrcStateForTests -} from '../../document-images/local-image-src-cache' + +import { resetLocalImageCacheState as resetLocalImageSrcStateForTests } from '../../document-images/local-image-src-cache' import { setRichMarkdownImageResolverContext } from './rich-markdown-image-context' -import { documentResourceAccess } from '@/lib/local-file-access' // The key the editor leases: rich markdown reads images as resources of their document. -function diagramCacheKey(): string { - const key = getLocalImageSrcCacheKey( - 'diagram.png', - '/repo/docs/readme.md', - undefined, - undefined, - documentResourceAccess('/repo/docs/readme.md') - ) - if (!key) { - throw new Error('diagram.png has no local image cache key') - } - return key -} async function flushPromises(): Promise { for (let index = 0; index < 5; index += 1) { @@ -86,27 +69,4 @@ describe('rich markdown local images', () => { editor.destroy() } }) - - it('keeps a displayed image leased when another surface releases the same cache entry', async () => { - const host = document.createElement('div') - document.body.appendChild(host) - const editor = new Editor({ - element: host, - extensions: createRichMarkdownExtensions({ codec: createRichMarkdownEditorCodec() }), - content: '![](diagram.png)', - contentType: 'markdown' - }) - - try { - setRichMarkdownImageResolverContext(editor, { filePath: '/repo/docs/readme.md' }) - await flushPromises() - - releaseLocalImageSrcByKey(diagramCacheKey()) - - expect(URL.revokeObjectURL).not.toHaveBeenCalledWith('blob:rich-local-image') - expect(host.querySelector('img')?.src).toBe('blob:rich-local-image') - } finally { - editor.destroy() - } - }) }) diff --git a/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownErrorBoundary.lazy-chunk.test.tsx b/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownErrorBoundary.lazy-chunk.test.tsx index 64fe89ad99e..bd5303b953c 100644 --- a/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownErrorBoundary.lazy-chunk.test.tsx +++ b/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownErrorBoundary.lazy-chunk.test.tsx @@ -106,31 +106,4 @@ describe('RichMarkdownErrorBoundary lazy chunk containment', () => { cause: `SyntaxError: ${CORRUPT_CHUNK_PARSE_ERROR}` }) }) - - it('still reports ordinary render errors', async () => { - const error = new Error('ordinary render failure') - function BrokenEditor(): ReactElement { - throw error - } - ;({ container, root } = createContainer()) - - await act(async () => { - root?.render( - - - - ) - }) - - expect(container?.textContent).toContain('rich markdown editor') - expect(recordBreadcrumbMock).not.toHaveBeenCalled() - expect(reportCrashMock).toHaveBeenCalledTimes(1) - expect(reportCrashMock).toHaveBeenCalledWith( - expect.objectContaining({ - boundaryId: 'editor.rich-markdown', - surface: 'rich-markdown-editor', - error - }) - ) - }) }) diff --git a/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-auto-focus.test.ts b/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-auto-focus.test.ts deleted file mode 100644 index b0c4e89ebd9..00000000000 --- a/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-auto-focus.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -// @vitest-environment happy-dom -import type { Editor } from '@tiptap/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { autoFocusRichEditor } from './rich-markdown-auto-focus' - -function createEditor( - focus = vi.fn(), - domFocus: (options?: FocusOptions) => void = vi.fn() -): Editor { - return { - isDestroyed: false, - commands: { focus }, - view: { dom: { focus: domFocus } } - } as unknown as Editor -} - -/** Identity-only stand-in for `document.activeElement`: the policy compares it, never reads it. */ -type StubbedActiveElement = Record - -function setupScheduledFocus( - activeElement: StubbedActiveElement | null, - force = false -): { - focus: ReturnType - runFrame: () => void -} { - let pendingFrame: FrameRequestCallback = () => { - throw new Error('expected focus frame to be scheduled') - } - const focus = vi.fn() - vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { - pendingFrame = callback - return 7 - }) - vi.stubGlobal('cancelAnimationFrame', vi.fn()) - vi.stubGlobal('document', { activeElement, body: {} }) - autoFocusRichEditor(createEditor(focus), null, force) - - return { - focus, - runFrame: () => pendingFrame(0) - } -} - -describe('autoFocusRichEditor', () => { - afterEach(() => { - vi.unstubAllGlobals() - document.body.replaceChildren() - }) - - it('claims DOM focus synchronously on an explicit handoff', () => { - const root = document.createElement('div') - const editorDom = document.createElement('div') - editorDom.tabIndex = -1 - root.append(editorDom) - document.body.append(root) - vi.stubGlobal( - 'requestAnimationFrame', - vi.fn(() => 11) - ) - vi.stubGlobal('cancelAnimationFrame', vi.fn()) - - autoFocusRichEditor(createEditor(vi.fn(), editorDom.focus.bind(editorDom)), root, true) - - expect(root.contains(document.activeElement)).toBe(true) - }) - - it('does not run deferred focus after an explicit handoff expires', () => { - let runFrame: FrameRequestCallback = () => {} - let requestActive = true - const focus = vi.fn() - vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { - runFrame = callback - return 13 - }) - vi.stubGlobal('cancelAnimationFrame', vi.fn()) - - autoFocusRichEditor(createEditor(focus), null, true, () => requestActive) - requestActive = false - runFrame(0) - - expect(focus).not.toHaveBeenCalled() - }) - - it('does not steal focus from other controls outside the editor', () => { - const { focus, runFrame } = setupScheduledFocus({}) - runFrame() - - expect(focus).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/editor/rich-markdown/links/rich-markdown-file-uri-links.test.ts b/src/renderer/src/components/editor/rich-markdown/links/rich-markdown-file-uri-links.test.ts index 67828b956d2..c05823c5db6 100644 --- a/src/renderer/src/components/editor/rich-markdown/links/rich-markdown-file-uri-links.test.ts +++ b/src/renderer/src/components/editor/rich-markdown/links/rich-markdown-file-uri-links.test.ts @@ -46,33 +46,3 @@ it.each(['file:///repo/notes/guide.md#section', 'file:///C:/repo/a%20b.md#L10']) expect(reopened.view.dom.querySelector('a')?.getAttribute('href')).toBe(uri) } ) - -it('keeps javascript: links unavailable through copy and paste', () => { - const source = createEditor({ - type: 'doc', - content: [ - { - type: 'paragraph', - content: [ - { - type: 'text', - text: 'guide', - marks: [{ type: 'link', attrs: { href: 'javascript:alert(1)' } }] - } - ] - } - ] - }) - expect(source.view.dom.querySelector('a')?.getAttribute('href')).toBe('') - const target = createEditor('') - paste(target, copy(source)) - expect(target.view.dom.querySelector('a')).toBeNull() - expect(target.getText()).toBe('guide') -}) - -it('does not turn pasted plain-text file URIs into links', () => { - const target = createEditor('') - target.view.pasteText('see file:///repo/notes/guide.md now') - expect(target.view.dom.querySelector('a')).toBeNull() - expect(target.getMarkdown()).toBe('see file:///repo/notes/guide.md now') -}) diff --git a/src/renderer/src/components/editor/rich-markdown/lists/rich-markdown-blockquote-list.test.ts b/src/renderer/src/components/editor/rich-markdown/lists/rich-markdown-blockquote-list.test.ts deleted file mode 100644 index 931dfc77ca8..00000000000 --- a/src/renderer/src/components/editor/rich-markdown/lists/rich-markdown-blockquote-list.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { Editor } from '@tiptap/core' -import { describe, expect, it } from 'vitest' -import { createRichMarkdownExtensions } from '../schema/rich-markdown-extensions' -import { createRichMarkdownEditorCodec } from '../document/rich-markdown-source-transport' -import { encodeRawMarkdownHtmlForRichEditor } from '../raw-source/raw-markdown-html' - -function openMarkdown(source: string): Editor { - const codec = createRichMarkdownEditorCodec() - return new Editor({ - element: null, - extensions: createRichMarkdownExtensions({ codec }), - content: encodeRawMarkdownHtmlForRichEditor(source, codec), - contentType: 'markdown' - }) -} - -describe('rich markdown blockquote list continuations', () => { - // A no-break space reaches the fallback (only Tiptap reads it); plain spaces are controls. - it.each(['1.\u00a0', '3)\u00a0', '1234567890.\u00a0', '1. ', '3) '])( - 'opens %j without throwing during Markdown initialization', - (marker) => { - const source = `> ${marker}first\ncontinued` - const codec = createRichMarkdownEditorCodec() - const editor = new Editor({ - element: null, - extensions: createRichMarkdownExtensions({ codec }), - content: encodeRawMarkdownHtmlForRichEditor(source, codec), - contentType: 'markdown' - }) - try { - expect(editor.getText()).toContain('first') - expect(editor.getText()).toContain('continued') - expect(editor.getJSON().content?.[0]?.type).toBe('blockquote') - expect(editor.getJSON().content?.[0]?.content?.[0]).toMatchObject({ - type: 'orderedList', - content: [{ type: 'listItem', content: [{ type: 'paragraph' }] }] - }) - const expectedCodec = createRichMarkdownEditorCodec() - const expected = new Editor({ - element: null, - extensions: createRichMarkdownExtensions({ codec: expectedCodec }), - content: encodeRawMarkdownHtmlForRichEditor( - `> ${marker}first\n> continued`, - expectedCodec - ), - contentType: 'markdown' - }) - try { - expect(editor.getJSON()).toEqual(expected.getJSON()) - } finally { - expected.destroy() - } - } finally { - editor.destroy() - } - } - ) - - it.each([ - ['> 1.\u00a0x\nlazy\n> 2.\u00a0y\nlazy2\n', '> 1. x\nlazy\n> 2. y\nlazy2\n'], - ['> 1.\u00a0x\nlazy\n> quoted para\n', '> 1. x\nlazy\n> quoted para\n'], - ['> 1.\u00a0x\n> > nested\nlazy', '> 1. x\n> > nested\nlazy'], - [ - '> 1.\u00a0x\n> > nested\n> > more\n> 2.\u00a0y\nlazy', - '> 1. x\n> > nested\n> > more\n> 2. y\nlazy' - ], - ['> 1.\u00a0x\nlazy\n > y', '> 1. x\nlazy\n > y'], - // Tiptap reads a 5+ space gap as text, not code; compare with the fully quoted form. - ['> 1.\u00a0 x\n> > nested\nlazy', '> 1.\u00a0 x\n> > nested\n> > lazy'] - ])('ends the continued list at the next quoted line: %j', (source, control) => { - const editor = openMarkdown(source) - const expected = openMarkdown(control) - try { - expect(editor.getJSON()).toEqual(expected.getJSON()) - expect(editor.getMarkdown()).toBe(expected.getMarkdown()) - } finally { - editor.destroy() - expected.destroy() - } - }) - - it('opens many quoted lazy continuations without nesting each into the last', () => { - const editor = openMarkdown('> 1.\u00a0x\nlazy\n'.repeat(1000)) - try { - expect(JSON.stringify(editor.getJSON()).match(/"blockquote"/g)).toHaveLength(1) - expect(editor.getText()).toContain('lazy') - } finally { - editor.destroy() - } - }) -}) diff --git a/src/renderer/src/components/editor/rich-markdown/raw-source/raw-markdown-html-line-break.test.ts b/src/renderer/src/components/editor/rich-markdown/raw-source/raw-markdown-html-line-break.test.ts index 4d9d79024ca..95d9f46ead3 100644 --- a/src/renderer/src/components/editor/rich-markdown/raw-source/raw-markdown-html-line-break.test.ts +++ b/src/renderer/src/components/editor/rich-markdown/raw-source/raw-markdown-html-line-break.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest' import { Editor } from '@tiptap/core' -import type { Node as ProseMirrorNode } from '@tiptap/pm/model' + import { createRichMarkdownEditorCodec } from '../document/rich-markdown-source-transport' import { createRichMarkdownExtensions } from '../schema/rich-markdown-extensions' import { encodeRawMarkdownHtmlForRichEditor } from './raw-markdown-html' @@ -17,51 +17,12 @@ function createEditor(markdown: string): Editor { }) } -function findRawInlineNodes(editor: Editor): ProseMirrorNode[] { - const nodes: ProseMirrorNode[] = [] - editor.state.doc.descendants((node) => { - if (node.type.name === 'rawMarkdownHtmlInline') { - nodes.push(node) - } - }) - return nodes -} - -function renderTag(node: ProseMirrorNode): string { - const spec = node.type.spec.toDOM?.(node) - return Array.isArray(spec) ? String(spec[0]) : '' -} - const TABLE_WITH_BREAKS = '| Field | Description |\n' + '| --- | --- |\n' + '| verdict | Values:

`normal`
`defect` |\n' describe('raw markdown
line breaks in the rich editor', () => { - it('renders
and
inside a table cell as real line breaks, not literal text', () => { - const editor = createEditor(TABLE_WITH_BREAKS) - try { - const breakNodes = findRawInlineNodes(editor) - expect(breakNodes.length).toBeGreaterThan(0) - for (const node of breakNodes) { - expect(renderTag(node)).toBe('br') - } - } finally { - editor.destroy() - } - }) - - it('keeps non-break inline HTML as an inert literal span', () => { - const editor = createEditor('Before hi after\n') - try { - const [spanNode] = findRawInlineNodes(editor) - expect(spanNode).toBeDefined() - expect(renderTag(spanNode)).toBe('span') - } finally { - editor.destroy() - } - }) - it('round-trips verbatim
tags after the rendered DOM is parsed again', () => { const editor = createEditor(TABLE_WITH_BREAKS) try { @@ -79,20 +40,6 @@ describe('raw markdown
line breaks in the rich editor', () => { } }) - it('preserves a case-insensitive break spelling through a DOM round trip', () => { - const editor = createEditor('Before
after\n') - try { - const rendered = document.createElement('div') - rendered.innerHTML = editor.getHTML() - - editor.commands.setContent(rendered.innerHTML) - - expect(editor.getMarkdown()).toContain('Before
after') - } finally { - editor.destroy() - } - }) - it('does not accept arbitrary Markdown source from a forged break marker', () => { const editor = createEditor('Before
after\n') try { diff --git a/src/renderer/src/components/editor/rich-markdown/review/rich-markdown-annotation-highlight.mapping.test.ts b/src/renderer/src/components/editor/rich-markdown/review/rich-markdown-annotation-highlight.mapping.test.ts index 5c895ee9dc2..1b035a861d6 100644 --- a/src/renderer/src/components/editor/rich-markdown/review/rich-markdown-annotation-highlight.mapping.test.ts +++ b/src/renderer/src/components/editor/rich-markdown/review/rich-markdown-annotation-highlight.mapping.test.ts @@ -47,19 +47,6 @@ describe('review highlight positions across edits and metadata', () => { expect(highlightedText(editor)).toEqual(['note']) }) - it('preserves mapped active and note ranges when metadata updates only one field', () => { - const editor = createEditor() - editor.view.dispatch(editor.state.tr.insertText('prefix ', 1)) - editor.view.dispatch( - editor.state.tr.setMeta(richMarkdownAnnotationHighlightPluginKey, { - noteRanges: [{ from: 15, to: 19 }] - }) - ) - const active = editor.view.dom.querySelector('.rich-markdown-annotation-selection-active') - expect(active?.textContent).toBe('note') - expect(highlightedText(editor)).toEqual(['note']) - }) - it('drops deleted highlights instead of recreating them over surviving text', () => { const editor = createEditor() editor.view.dispatch(editor.state.tr.delete(8, 12)) @@ -72,16 +59,6 @@ describe('review highlight positions across edits and metadata', () => { expect(highlightedText(editor)).toEqual([]) }) - it('maps retained notes while accepting new-document metadata in the same edit transaction', () => { - const editor = createEditor() - editor.view.dispatch( - editor.state.tr.insertText('prefix ', 1).setMeta(richMarkdownAnnotationHighlightPluginKey, { - activeRange: null - }) - ) - expect(highlightedText(editor)).toEqual(['note']) - }) - it('excludes boundary insertions and keeps undo/redo positions after rebuilding', () => { const editor = createEditor() editor.view.dispatch(editor.state.tr.insertText('end', 12).insertText('start', 8)) diff --git a/src/renderer/src/components/editor/rich-markdown/schema/rich-markdown-trailing-paragraph.test.ts b/src/renderer/src/components/editor/rich-markdown/schema/rich-markdown-trailing-paragraph.test.ts index e20d7de368f..89bf23aa1be 100644 --- a/src/renderer/src/components/editor/rich-markdown/schema/rich-markdown-trailing-paragraph.test.ts +++ b/src/renderer/src/components/editor/rich-markdown/schema/rich-markdown-trailing-paragraph.test.ts @@ -56,15 +56,6 @@ describe('the synthetic trailing paragraph', () => { expect(editor.getMarkdown()).toBe('> Quote\n\nNew paragraph') }) - it('keeps an intentionally added blank paragraph', () => { - const editor = createEditor('> Quote') - editor.commands.setTextSelection(2) - editor.commands.setTextSelection(editor.state.doc.content.size - 1) - editor.commands.splitBlock() - expect(createEditor(editor.getMarkdown()).getJSON()).toEqual(editor.getJSON()) - expect(editor.state.doc.childCount).toBe(3) - }) - it('keeps authored trailing blank paragraphs after loading and replacing content', () => { const editor = createEditor('> Quote\n\n') editor.commands.setTextSelection(2) diff --git a/src/renderer/src/components/editor/rich-markdown/tables/use-rich-markdown-table-context-menu.test.tsx b/src/renderer/src/components/editor/rich-markdown/tables/use-rich-markdown-table-context-menu.test.tsx index 9b3cfcbd5ac..44c762aa8ba 100644 --- a/src/renderer/src/components/editor/rich-markdown/tables/use-rich-markdown-table-context-menu.test.tsx +++ b/src/renderer/src/components/editor/rich-markdown/tables/use-rich-markdown-table-context-menu.test.tsx @@ -74,36 +74,4 @@ describe('rich markdown table context menu', () => { editorElement.remove() } }) - - it('reports header targets so native row actions can be disabled', () => { - const editorElement = document.createElement('div') - document.body.append(editorElement) - const editor = new Editor({ - element: editorElement, - extensions: createRichMarkdownExtensions({ codec: createRichMarkdownEditorCodec() }), - content: TABLE, - contentType: 'markdown' - }) - const setRichMarkdownContextMenuTarget = vi.fn() - Object.defineProperty(window, 'api', { - configurable: true, - value: { - ui: { - onRichMarkdownContextCommand: vi.fn(() => vi.fn()), - setRichMarkdownContextMenuTarget - } - } - }) - const view = render() - try { - fireEvent.contextMenu(editorElement.querySelector('th')!, { clientX: 8, clientY: 9 }) - expect(setRichMarkdownContextMenuTarget).toHaveBeenLastCalledWith( - expect.objectContaining({ cellType: 'header', x: 8, y: 9 }) - ) - } finally { - view.unmount() - editor.destroy() - editorElement.remove() - } - }) }) diff --git a/src/renderer/src/components/editor/save/commands/editor-file-save-utf8-conversion.test.ts b/src/renderer/src/components/editor/save/commands/editor-file-save-utf8-conversion.test.ts index 6ca2f16850a..48dfd267e84 100644 --- a/src/renderer/src/components/editor/save/commands/editor-file-save-utf8-conversion.test.ts +++ b/src/renderer/src/components/editor/save/commands/editor-file-save-utf8-conversion.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { toast } from 'sonner' import { createEditorStore } from '../../autosave/editor-autosave-controller-test-fixture' import { attachEditorAutosaveController } from '../../autosave/editor-autosave-controller' -import { attemptEditorFileSave, confirmEditorUtf8Conversion } from './editor-file-save-attempt' +import { attemptEditorFileSave } from './editor-file-save-attempt' import { GUARDED_PATH, openGuardedFile, @@ -61,28 +61,3 @@ it('writes UTF-8 once the user confirms the conversion', async () => { cleanup() } }) - -it('reports the refusal when no one can be asked', async () => { - const { disk, id, cleanup } = openLatin1() - try { - expect(await attemptEditorFileSave({ fileId: id })).toBe(false) - expect(disk.files.get(GUARDED_PATH)).toBe(LATIN1) - expect(vi.mocked(toast.error).mock.calls[0]?.[0]).toBe( - "This file isn't UTF-8 text, so it wasn't saved." - ) - } finally { - cleanup() - } -}) - -it('words the confirmation as a lossy, destructive conversion', async () => { - const confirm = vi.fn(async () => true) - await confirmEditorUtf8Conversion(confirm, '/repo/notes.md') - expect(confirm).toHaveBeenCalledWith({ - title: 'Save notes.md as UTF-8?', - description: - "This file isn't UTF-8 text. Saving it as UTF-8 replaces any characters that aren't valid UTF-8 with �, and the original bytes can't be recovered.", - confirmLabel: 'Save as UTF-8', - confirmVariant: 'destructive' - }) -}) diff --git a/src/renderer/src/components/editor/save/flush/removal-unsaved-editor-files.test.ts b/src/renderer/src/components/editor/save/flush/removal-unsaved-editor-files.test.ts deleted file mode 100644 index b35a6377130..00000000000 --- a/src/renderer/src/components/editor/save/flush/removal-unsaved-editor-files.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { AppState } from '@/store/types' -import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { registerPendingEditorFlush } from './editor-pending-flush' -import { - collectRemovalUnsavedFiles, - flushRemovalPendingEdits, - lastViewUnsavedFiles -} from './removal-unsaved-editor-files' - -// Every tab of a path shares one model in this fixture. -vi.mock('../../model-lifetime/identity/editor-model-owner', () => ({ - resolveEditorModelOwner: () => ({ environmentId: null, hostId: 'local' }), - getEditorModelOwnerKey: () => '' -})) - -function tab(id: string, filePath: string, worktreeId: string, extra: Partial = {}) { - const file: OpenFile = { - id, - filePath, - relativePath: id, - worktreeId, - language: 'plaintext', - isDirty: true, - mode: 'edit', - ...extra - } - return file -} - -function state(openFiles: OpenFile[], extra: Record = {}): AppState { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these readers touch only the listed fields; the owner module is mocked. - return { - openFiles, - editorDrafts: {}, - editorBufferIdOf: Object.fromEntries(openFiles.map((file) => [file.id, file.id])), - editorBufferViews: Object.fromEntries(openFiles.map((file) => [file.id, [file.id]])), - worktreesByRepo: {}, - detectedWorktreesByRepo: {}, - folderWorkspaces: [], - projectGroups: [], - markdownViewMode: {}, - editorViewMode: {}, - ...extra - } as unknown as AppState -} - -describe('lastViewUnsavedFiles', () => { - it('lists closing tabs with unsaved text only', () => { - const s = state( - [ - tab('dirty', '/w/a.ts', 'wt'), - tab('clean', '/w/b.ts', 'wt', { isDirty: false }), - tab('drafted', '/w/c.ts', 'wt', { isDirty: false }), - tab('elsewhere', '/o/d.ts', 'other') - ], - { editorDrafts: { drafted: 'typed' } } - ) - expect( - lastViewUnsavedFiles(s, new Set(['dirty', 'clean', 'drafted'])).map((f) => f.id) - ).toEqual(['dirty', 'drafted']) - }) - - it('includes editable unstaged diff tabs and skips read-only views', () => { - const s = state([ - tab('unstaged', '/w/a.ts', 'wt', { mode: 'diff', diffSource: 'unstaged' }), - tab('staged', '/w/b.ts', 'wt', { mode: 'diff', diffSource: 'staged' }), - tab('readonly', '/w/c.ts', 'wt', { readOnly: true }) - ]) - expect( - lastViewUnsavedFiles(s, new Set(['unstaged', 'staged', 'readonly'])).map((f) => f.id) - ).toEqual(['unstaged']) - }) - - it('skips a file whose record still has a view that stays open', () => { - const shared = state([tab('a', '/w/a.ts', 'wt'), tab('b', '/w/a.ts', 'other')], { - editorBufferIdOf: { a: 'rec', b: 'rec' }, - editorBufferViews: { rec: ['a', 'b'] } - }) - expect(lastViewUnsavedFiles(shared, new Set(['a']))).toEqual([]) - - expect(lastViewUnsavedFiles(shared, new Set(['a', 'b']))).toHaveLength(1) - }) -}) - -describe('collectRemovalUnsavedFiles', () => { - it('uses the tabs the purge would close, after flushing their delayed views', () => { - const flushed = vi.fn() - const kept = vi.fn() - const unregisterFlushed = registerPendingEditorFlush('a', flushed) - const unregisterKept = registerPendingEditorFlush('b', kept) - const s = state([tab('a', '/w/a.md', 'wt'), tab('b', '/o/b.md', 'other')]) - - const files = collectRemovalUnsavedFiles(() => s, [{ id: 'wt' }]) - - expect(files.map((f) => f.id)).toEqual(['a']) - expect(flushed).toHaveBeenCalledTimes(1) - expect(kept).not.toHaveBeenCalled() - unregisterFlushed() - unregisterKept() - }) - - it('keeps going when a delayed view fails to flush', () => { - const error = vi.spyOn(console, 'error').mockImplementation(() => {}) - const unregister = registerPendingEditorFlush('a', () => { - throw new Error('boom') - }) - flushRemovalPendingEdits(state([tab('a', '/w/a.md', 'wt')]), ['a']) - expect(error).toHaveBeenCalled() - unregister() - error.mockRestore() - }) -}) diff --git a/src/renderer/src/components/editor/save/queue/editor-save-lossless-baseline.test.ts b/src/renderer/src/components/editor/save/queue/editor-save-lossless-baseline.test.ts index efce47c7bf6..3bae8db42db 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-lossless-baseline.test.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-lossless-baseline.test.ts @@ -16,34 +16,6 @@ afterEach(() => { __clearNonUtf8AutosavePausesForTests() }) -it.each([ - ['autosave', 'failed'], - ['restart', 'failed'], - ['user', 'not-utf8'], - ['convert', 'written'], - ['overwrite', 'written'] -] as const)('a lossy baseline needs consent to write (%s: %s)', async (trigger, expected) => { - const decoded = Buffer.from([0x61, 0xfe]).toString('utf8') - const newer = Buffer.from([0x61, 0xff]).toString('utf8') - const disk = stubGuardedDisk({ [GUARDED_PATH]: newer }) - const store = createEditorStore() - openGuardedFile(store, { baseline: decoded, draft: decoded }) - const queue = createEditorSaveQueue(store) - try { - const automatic = trigger === 'autosave' || trigger === 'restart' - expect(await queue.queueSave(store.getState().openFiles[0], decoded, trigger)).toBe(expected) - expect(store.getState().openFiles[0]?.isDirty).toBe(expected !== 'written') - // Why: a non-UTF-8 refusal is not a changed-on-disk conflict. - expect(store.getState().openFiles[0]?.externalMutation).toBeUndefined() - // Why: an explicit save asks to convert instead of pausing autosave with a notice. - expect(isAutosaveSuspendedForFile(store.getState().openFiles[0]!)).toBe(automatic) - expect(toast.warning).toHaveBeenCalledTimes(automatic ? 1 : 0) - expect(disk.files.get(GUARDED_PATH)).toBe(expected === 'written' ? decoded : newer) - } finally { - queue.dispose() - } -}) - it('pauses autosave once for a non-UTF-8 file until a confirmed explicit save converts it', async () => { const latin1 = Buffer.from([0x63, 0x61, 0x66, 0xe9]).toString('utf8') const disk = stubGuardedDisk({ [GUARDED_PATH]: latin1 }) diff --git a/src/renderer/src/components/editor/useEditorPanelActiveTabContentLoad.overview.test.tsx b/src/renderer/src/components/editor/useEditorPanelActiveTabContentLoad.overview.test.tsx deleted file mode 100644 index fa425f542ef..00000000000 --- a/src/renderer/src/components/editor/useEditorPanelActiveTabContentLoad.overview.test.tsx +++ /dev/null @@ -1,102 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' -import type { OpenFile } from '@/store/slices/editor' -import { makeWorktree } from '@/store/slices/worktrees-slice-test-fixtures' -import type { GitStatusEntry } from '../../../../shared/git/status/git-status-types' -import { useEditorPanelActiveTabContentLoad } from './useEditorPanelActiveTabContentLoad' - -// The active tab's load is a user act that may start a stopped WSL distro. -const WAKE = { wakeWslDistro: true } - -const PATH = '/repo/file.ts' -const ENTRY: GitStatusEntry = { - path: 'file.ts', - status: 'modified', - area: 'unstaged', - conflictKind: 'both_modified', - conflictStatus: 'unresolved', - conflictStatusSource: 'git' -} - -const state = () => useAppStore.getState() - -function openView(worktreeId: string): OpenFile { - state().openFile({ - filePath: PATH, - relativePath: 'file.ts', - worktreeId, - language: 'typescript', - mode: 'edit' - }) - return state().openFiles.find((file) => file.worktreeId === worktreeId && file.mode === 'edit')! -} - -beforeEach(() => { - useAppStore.setState(useAppStore.getInitialState(), true) - useAppStore.setState({ - worktreesByRepo: { - 'repo-1': [ - makeWorktree({ id: 'wt-1', repoId: 'repo-1', path: '/repo', hostId: 'local' }), - makeWorktree({ id: 'wt-2', repoId: 'repo-1', path: '/repo', hostId: 'local' }) - ] - } - }) -}) - -afterEach(cleanup) - -describe('conflict-review overview loads', () => { - it('reload under the new id when the borrowed view closes or another opens', () => { - const view = openView('wt-1') - state().openConflictReview( - 'wt-2', - '/repo', - [{ path: 'file.ts', conflictKind: 'both_modified' }], - 'live-summary' - ) - const review = state().openFiles.find((file) => file.mode === 'conflict-review')! - const loadFileContent = vi.fn(async () => {}) - // Why stable inputs: only the store's view changes may rerun the load. - const gitStatusEntries = [ENTRY] - const refs = { - fileContents: {}, - diffContents: {}, - fileReadGenerationRef: { current: {} }, - outstandingFileReadsRef: { current: {} }, - diffReadGenerationRef: { current: {} }, - outstandingDiffReadsRef: { current: {} }, - loadDiffContent: vi.fn(async () => {}) - } - renderHook(() => - useEditorPanelActiveTabContentLoad({ - activeFile: review, - selectedConflictReviewFile: null, - isVisible: true, - isChangesMode: false, - gitStatusEntries, - ...refs, - loadFileContent - }) - ) - expect(loadFileContent).toHaveBeenLastCalledWith(PATH, view.id, 'wt-1', 'file.ts', WAKE) - - act(() => state().closeFile(view.id)) - // Re-keying under the same active tab is not a user act, so it reads without waking. - expect(loadFileContent).toHaveBeenLastCalledWith(PATH, PATH, 'wt-2', 'file.ts', undefined) - - let reopened: OpenFile | undefined - act(() => { - reopened = openView('wt-1') - }) - expect(loadFileContent).toHaveBeenLastCalledWith( - PATH, - reopened!.id, - 'wt-1', - 'file.ts', - undefined - ) - expect(loadFileContent).toHaveBeenCalledTimes(3) - }) -}) diff --git a/src/renderer/src/components/landing-preflight-unverifiable-host.test.tsx b/src/renderer/src/components/landing-preflight-unverifiable-host.test.tsx deleted file mode 100644 index de39f7202bb..00000000000 --- a/src/renderer/src/components/landing-preflight-unverifiable-host.test.tsx +++ /dev/null @@ -1,104 +0,0 @@ -// @vitest-environment happy-dom - -import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - RuntimeHostStatusSnapshot, - RuntimeEnvironmentStatus -} from '../../../shared/remote-runtime/host-status/runtime-host-status' -import type { RuntimeStatus } from '../../../shared/runtime-types' -import { useAppStore } from '../store' - -import { useLandingPreflightRuntime } from './landing-preflight-runtime' -import { getDefaultSettings } from '../../../shared/constants' - -const ENVIRONMENT_ID = 'environment-a' -const initialState = useAppStore.getInitialState() -const invalidate = vi.fn() -const refresh = vi.fn(async () => {}) - -function makeStatus(): RuntimeStatus { - return { - runtimeId: 'runtime-a', - rendererGraphEpoch: 0, - graphStatus: 'ready', - authoritativeWindowId: null, - liveTabCount: 0, - liveLeafCount: 0 - } -} - -function snapshot(overrides: Partial = {}): RuntimeHostStatusSnapshot { - return { - environmentId: ENVIRONMENT_ID, - pairingRevision: 1, - sequence: 1, - checkedAt: 1, - status: makeStatus(), - verification: 'verified', - transport: 'ready', - ...overrides - } -} - -function setStatusEntry(entry: RuntimeEnvironmentStatus): void { - useAppStore.setState({ - runtimeStatusByEnvironmentId: new Map([[ENVIRONMENT_ID, entry]]) - }) -} - -describe('landing preflight under an unverifiable host probe', () => { - beforeEach(() => { - invalidate.mockClear() - refresh.mockClear() - useAppStore.setState( - { - ...initialState, - settings: { ...getDefaultSettings('/tmp'), activeRuntimeEnvironmentId: ENVIRONMENT_ID }, - invalidatePreflightStatus: invalidate, - refreshPreflightStatus: refresh - }, - true - ) - setStatusEntry({ status: makeStatus(), snapshot: snapshot(), checkedAt: 1 }) - }) - - afterEach(() => { - cleanup() - useAppStore.setState(initialState, true) - }) - - it('keeps preflight state when a ready host answers an unverifiable probe', () => { - renderHook(() => useLandingPreflightRuntime()) - expect(invalidate).not.toHaveBeenCalled() - - act(() => { - setStatusEntry({ - status: null, - snapshot: snapshot({ sequence: 2, checkedAt: 2, verification: 'unavailable' }), - checkedAt: 2 - }) - }) - - expect(invalidate).not.toHaveBeenCalled() - }) - - it('still discards preflight state once the transport goes down', () => { - renderHook(() => useLandingPreflightRuntime()) - - act(() => { - setStatusEntry({ - status: null, - snapshot: snapshot({ - sequence: 2, - checkedAt: 2, - verification: 'unavailable', - transport: 'disconnected' - }), - checkedAt: 2 - }) - }) - - expect(invalidate).toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/onboarding/onboarding-theme-look-settings.test.ts b/src/renderer/src/components/onboarding/onboarding-theme-look-settings.test.ts deleted file mode 100644 index 5c63666a9e7..00000000000 --- a/src/renderer/src/components/onboarding/onboarding-theme-look-settings.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getDefaultSettings } from '../../../../shared/constants' -import { MATCH_TERMINAL_APP_THEME } from '../../../../shared/plugin-theme-settings' -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 { buildThemeLooks, type ThemeLook, type ThemeLookBase } from './onboarding-theme-looks' -import { selectedThemeLookId, themeLookSettingsUpdate } from './onboarding-theme-look-settings' - -const labels = { orca: 'Orca', community: 'Terminal palette', builtIn: (b: ThemeLookBase) => b } -const appTheme: PluginThemeRegistration = { - id: 'plugin:gh/github-dark-default', - base: 'dark', - tokens: { '--background': '#0d1117', '--foreground': '#e6edf3' }, - revision: '1', - pluginKey: 'gh', - pluginName: 'GitHub Themes', - label: 'GitHub Dark Default' -} -const terminalTheme: PluginTerminalThemeRegistration = { - id: 'plugin:gh/github-dark-default', - pluginKey: 'gh', - pluginName: 'GitHub Themes', - label: 'GitHub Dark Default', - mode: 'dark', - terminal: { background: '#010409', foreground: '#e6edf3', red: '#ff7b72' } -} - -function setup(overrides: Partial = {}) { - const settings: GlobalSettings = { ...getDefaultSettings('/home/test'), ...overrides } - const looks = (base: ThemeLookBase): ThemeLook[] => - buildThemeLooks({ - base, - pluginThemes: [appTheme], - pluginTerminalThemes: [terminalTheme], - baseline: settings, - labels - }) - const look = (base: ThemeLookBase, id: string): ThemeLook => - looks(base).find((candidate) => candidate.id === id)! - const pick = (current: GlobalSettings, chosen: ThemeLook): GlobalSettings => ({ - ...current, - ...themeLookSettingsUpdate(chosen, current, settings, [terminalTheme]) - }) - return { settings, looks, look, pick } -} - -describe('themeLookSettingsUpdate', () => { - it('paints a terminal palette app-wide and drops overrides that would mask it', () => { - const { settings, look, looks, pick } = setup({ - terminalColorOverrides: { background: '#123456' } - }) - const next = pick(settings, look('dark', 'terminal:Dracula')) - - expect(next.pluginAppThemeDark).toBe(MATCH_TERMINAL_APP_THEME) - expect(next.terminalThemeDark).toBe('Dracula') - expect(next.terminalColorOverrides).toBeUndefined() - expect(selectedThemeLookId(next, 'dark', looks('dark'))).toBe('terminal:Dracula') - }) - - it('replaces an earlier pick in the same mode with the baseline before applying', () => { - const { settings, look, looks, pick } = setup() - const afterPalette = pick(settings, look('dark', 'terminal:Dracula')) - const next = pick(afterPalette, look('dark', appTheme.id)) - - expect(next.pluginAppThemeDark).toBe(appTheme.id) - // The plugin's own terminal palette replaces Dracula rather than layering on it. - expect(next.terminalThemeDark).not.toBe('Dracula') - expect(selectedThemeLookId(next, 'dark', looks('dark'))).toBe(appTheme.id) - - const reset = pick(next, look('dark', 'built-in:dark')) - expect(reset.pluginAppThemeDark).toBeNull() - expect(reset.terminalThemeDark).toBe(settings.terminalThemeDark) - }) - - it('leaves the other mode untouched and keeps light palettes off the dark terminal', () => { - const { settings, look, pick } = setup({ terminalUseSeparateLightTheme: false }) - const dark = pick(settings, look('dark', 'terminal:Dracula')) - const next = pick(dark, look('light', 'terminal:Catppuccin Latte')) - - expect(next.pluginAppThemeDark).toBe(MATCH_TERMINAL_APP_THEME) - expect(next.terminalThemeDark).toBe('Dracula') - expect(next.terminalThemeLight).toBe('Catppuccin Latte') - expect(next.terminalUseSeparateLightTheme).toBe(true) - }) -}) diff --git a/src/renderer/src/components/orchestration-crew/orchestration-panel-enabled.test.tsx b/src/renderer/src/components/orchestration-crew/orchestration-panel-enabled.test.tsx deleted file mode 100644 index f03a3866430..00000000000 --- a/src/renderer/src/components/orchestration-crew/orchestration-panel-enabled.test.tsx +++ /dev/null @@ -1,65 +0,0 @@ -// @vitest-environment happy-dom -import '@testing-library/jest-dom/vitest' -import { act, cleanup, render, screen } from '@testing-library/react' -import type { ComponentProps } from 'react' -import { afterEach, expect, it, vi } from 'vitest' -import { getDefaultSettings } from '../../../../shared/constants' -import { useAppStore } from '@/store/index' -import { NativeChatCrewFrame } from './NativeChatCrewPanel' -import { TerminalCrewPortals } from './TerminalCrewPortals' -import { ExperimentalPane } from '../settings/advanced/ExperimentalPane' -import { getExperimentalPaneSearchEntries } from '../settings/advanced/experimental-search' -import { TooltipProvider } from '../ui/tooltip' - -const initialState = useAppStore.getState() -afterEach(() => { - cleanup() - useAppStore.setState(initialState, true) - vi.unstubAllGlobals() -}) - -it('keeps the panel suspended when an existing user hydrates a saved opt-in', async () => { - const saved = { ...getDefaultSettings('/home/test'), experimentalOrchestrationPanel: true } - vi.stubGlobal('api', { settings: { get: vi.fn().mockResolvedValue(saved) } }) - useAppStore.setState({ settings: null }) - const controller: ComponentProps['controller'] = { - tabId: 'terminal', - worktreeId: 'workspace', - managerRef: { current: null }, - paneTransportsRef: { current: new Map() }, - isRendererVisible: true, - expandedPaneId: null, - isolatedPaneKey: null, - get managedPanes(): never { - throw new Error('Suspended panel must not discover terminal panes') - }, - effectiveChatViewMode: false, - chatPane: null - } - const content = () => ( - }> - - Transcript - - ) - const view = render(content()) - const transcript = screen.getByText('Transcript') - await act(async () => useAppStore.getState().fetchSettings()) - view.rerender(content()) - expect(screen.queryByRole('complementary')).not.toBeInTheDocument() - expect(screen.getByText('Transcript')).toBe(transcript) -}) - -it('offers no orchestration opt-in in Settings or its search catalog', () => { - const settings = { ...getDefaultSettings('/home/test'), experimentalOrchestrationPanel: true } - useAppStore.setState({ settings }) - const view = render( - - - - ) - expect(view.container.querySelector('#experimental-orchestration-panel')).toBeNull() - expect(getExperimentalPaneSearchEntries().map((entry) => entry.targetSectionId)).not.toContain( - 'experimental-orchestration-panel' - ) -}) diff --git a/src/renderer/src/components/pull-request-page/files/combined-diff-section-index.test.tsx b/src/renderer/src/components/pull-request-page/files/combined-diff-section-index.test.tsx deleted file mode 100644 index 5393e662b03..00000000000 --- a/src/renderer/src/components/pull-request-page/files/combined-diff-section-index.test.tsx +++ /dev/null @@ -1,111 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { GitHubPRFile } from '../../../../../shared/github/pull-request-types' -import type { PRFilesCombinedDiffViewerProps } from '@/components/github/pr-file-diff-mapping' - -const capturedSectionIndexMaps = vi.hoisted(() => ({ list: [] as ReadonlyMap[] })) -const loaders = vi.hoisted(() => ({ loadSection: (_index: number) => {} })) - -vi.mock('@/store', () => ({ - useAppStore: (selector: (state: Record) => unknown) => - selector({ settings: { theme: 'dark' } }) -})) - -vi.mock('../../editor/combined-diff/browse-files/combined-diff-file-tree', () => ({ - CombinedDiffFileTree: (props: { sectionIndexByKey: ReadonlyMap }) => { - capturedSectionIndexMaps.list.push(props.sectionIndexByKey) - return null - } -})) - -vi.mock('@/components/editor/diff/sections/DiffSectionItem', () => ({ - DiffSectionItem: () => null -})) -vi.mock('./toolbar', () => ({ PRFilesDiffToolbar: () => null })) -vi.mock('./view-restore', () => ({ usePRFilesDiffViewPersistence: () => {} })) - -vi.mock('./section-loader', () => ({ - usePRFileSectionLoader: ({ - setSections - }: { - setSections: (updater: (prev: { key: string; loading: boolean }[]) => unknown) => void - }) => { - // Simulate a fetched section patch with new array identity and unchanged section keys. - loaders.loadSection = (index: number) => { - setSections((prev) => - prev.map((section, sectionIndex) => - sectionIndex === index ? { ...section, loading: false } : section - ) - ) - } - return { - loadSection: loaders.loadSection, - retrySection: () => {}, - toggleSection: () => {}, - setAllSectionsCollapsed: () => {} - } - } -})) - -const { PRFilesCombinedDiffViewer } = await import('./combined-diff-viewer') - -let host: HTMLDivElement -let root: Root - -beforeEach(() => { - globalThis.IS_REACT_ACT_ENVIRONMENT = true - capturedSectionIndexMaps.list = [] - host = document.createElement('div') - document.body.appendChild(host) - root = createRoot(host) -}) - -afterEach(() => { - act(() => root.unmount()) - host.remove() - vi.restoreAllMocks() -}) - -function prFiles(count: number): GitHubPRFile[] { - return Array.from({ length: count }, (_, index) => ({ - path: `src/file-${String(index).padStart(3, '0')}.ts`, - status: 'modified' as const, - additions: 1, - deletions: 1, - isBinary: false - })) -} - -const viewerProps: PRFilesCombinedDiffViewerProps = { - files: prFiles(6), - comments: [], - repoPath: '/repo', - repoId: 'repo-1', - prNumber: 7, - prUrl: 'https://example.test/pr/7', - headSha: 'head', - baseSha: 'base', - pendingViewedPaths: new Set(), - onCommentAdded: () => {}, - onViewedChange: () => Promise.resolve(true) -} - -describe('pull request page combined diff section index map', () => { - it('keeps one map identity across on-demand section loads', () => { - act(() => { - root.render() - }) - capturedSectionIndexMaps.list = [] - - for (let index = 0; index < viewerProps.files.length; index += 1) { - act(() => loaders.loadSection(index)) - } - - expect(capturedSectionIndexMaps.list.length).toBe(viewerProps.files.length) - expect(capturedSectionIndexMaps.list[0]?.size).toBe(viewerProps.files.length) - expect(new Set(capturedSectionIndexMaps.list).size).toBe(1) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/plugin-panels/health/plugin-panel-watchdog-visibility.test.ts b/src/renderer/src/components/right-sidebar/plugin-panels/health/plugin-panel-watchdog-visibility.test.ts deleted file mode 100644 index 60eb4edaa66..00000000000 --- a/src/renderer/src/components/right-sidebar/plugin-panels/health/plugin-panel-watchdog-visibility.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createPanelWatchdog } from './plugin-panel-watchdog' -import { resetStaleDocumentVisibilityForTesting } from '../../../terminal-pane/stale-document-visibility' - -function setVisibility(state: 'visible' | 'hidden'): void { - Object.defineProperty(document, 'visibilityState', { value: state, configurable: true }) - document.dispatchEvent(new Event('visibilitychange')) -} - -describe('createPanelWatchdog visibility parking', () => { - beforeEach(() => { - vi.useFakeTimers() - setVisibility('visible') - resetStaleDocumentVisibilityForTesting() - }) - afterEach(() => { - vi.useRealTimers() - setVisibility('visible') - resetStaleDocumentVisibilityForTesting() - }) - - it('parks pings while hidden and resumes on the becoming-visible pass, not the next interval', () => { - const sendPing = vi.fn() - const watchdog = createPanelWatchdog({ - sendPing, - onUnresponsive: vi.fn(), - pingIntervalMs: 10_000, - pongTimeoutMs: 5_000 - }) - - watchdog.start() - expect(sendPing).toHaveBeenCalledTimes(1) - watchdog.handlePong(0) - - setVisibility('hidden') - vi.advanceTimersByTime(30_000) - expect(sendPing).toHaveBeenCalledTimes(1) - - // The resume pings immediately rather than waiting out the remaining interval. - setVisibility('visible') - expect(sendPing).toHaveBeenCalledTimes(2) - - watchdog.stop() - }) - - it('does not park forever when macOS wedges visibilityState at hidden', () => { - const sendPing = vi.fn() - const watchdog = createPanelWatchdog({ - sendPing, - onUnresponsive: vi.fn(), - pingIntervalMs: 10_000, - pongTimeoutMs: 5_000 - }) - - watchdog.start() - watchdog.handlePong(0) - setVisibility('hidden') - vi.advanceTimersByTime(20_000) - expect(sendPing).toHaveBeenCalledTimes(1) - - // Input proves hidden occlusion state is stale; resume pings without waiting for visibilitychange. - document.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true })) - expect(sendPing).toHaveBeenCalledTimes(2) - - watchdog.stop() - }) - - it('removes its visibility listener on stop', () => { - const sendPing = vi.fn() - const watchdog = createPanelWatchdog({ - sendPing, - onUnresponsive: vi.fn(), - pingIntervalMs: 10_000, - pongTimeoutMs: 5_000 - }) - - watchdog.start() - watchdog.handlePong(0) - watchdog.stop() - const callsAtStop = sendPing.mock.calls.length - - setVisibility('hidden') - setVisibility('visible') - expect(sendPing).toHaveBeenCalledTimes(callsAtStop) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control/commit/discard-all-failure-description.test.tsx b/src/renderer/src/components/right-sidebar/source-control/commit/discard-all-failure-description.test.tsx deleted file mode 100644 index d3f662c948d..00000000000 --- a/src/renderer/src/components/right-sidebar/source-control/commit/discard-all-failure-description.test.tsx +++ /dev/null @@ -1,105 +0,0 @@ -// @vitest-environment happy-dom - -import { act, renderHook } from '@testing-library/react' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { - DiscardAllDeps, - DiscardAllResult, - DiscardAllArea -} from '../../../../../../shared/source-control/listing/source-control-discard-all-sequence' -import type { SourceControlToastTestOptions } from './source-control-toast-test-options' -type DiscardAllRunner = ( - area: DiscardAllArea, - paths: readonly string[], - deps: DiscardAllDeps -) => Promise - -const mocks = vi.hoisted(() => ({ - toastError: vi.fn<(title: string, options?: SourceControlToastTestOptions) => void>(), - runDiscardAllForArea: vi.fn() -})) - -vi.mock('sonner', () => ({ toast: { error: mocks.toastError, dismiss: vi.fn() } })) -vi.mock('@/lib/connection-context', () => ({ getConnectionId: () => undefined })) -vi.mock('@/runtime/runtime-git-working-tree-client', () => ({ - bulkUnstageRuntimeGitPaths: vi.fn() -})) -vi.mock( - '../../../../../../shared/source-control/listing/source-control-discard-all-sequence', - () => ({ - getDiscardAllPaths: () => [], - runDiscardAllForArea: (area: DiscardAllArea, paths: readonly string[], deps: DiscardAllDeps) => - mocks.runDiscardAllForArea(area, paths, deps) - }) -) - -import { useSourceControlDiscardConfirmation } from './use-discard-confirmation' -import type { SourceControlEntryGroups } from '../../../../../../shared/source-control/listing/source-control-section-order' - -const EMPTY_GROUPS: SourceControlEntryGroups = { unstaged: [], staged: [], untracked: [] } - -function lastDescription(): string | undefined { - return mocks.toastError.mock.lastCall?.[1]?.description -} - -function renderDiscard() { - return renderHook(() => - useSourceControlDiscardConfirmation({ - activeRepoTarget: { kind: 'local' }, - activeWorktreeId: 'wt-1', - worktreePath: '/repo', - grouped: EMPTY_GROUPS, - isExecutingBulk: false, - setIsExecutingBulk: () => {}, - clearSelection: () => {}, - discardMany: async () => {}, - discardSingle: async () => {}, - refreshActiveGitStatusAfterMutation: async () => {} - }) - ) -} - -async function confirmDiscardOf( - paths: string[], - area: 'staged' | 'unstaged' = 'unstaged' -): Promise { - const { result } = renderDiscard() - await act(async () => { - result.current.requestDiscardPaths(area, paths) - }) - await act(async () => { - result.current.confirmPendingDiscard() - }) -} - -const WRAPPED = "Error invoking remote method 'git:discard': Error: index.lock exists" - -describe('discard-all failure descriptions', () => { - beforeEach(() => { - vi.clearAllMocks() - }) - - it('unwraps the IPC transport noise on a partial failure, like the per-row toast does', async () => { - mocks.runDiscardAllForArea.mockImplementation(async (_area, _paths, handlers) => { - handlers.onError?.(new Error(WRAPPED)) - return { aborted: false, discarded: [], failed: ['a.ts'] } - }) - - await confirmDiscardOf(['a.ts']) - - expect(lastDescription()).toContain('index.lock exists') - expect(lastDescription()).not.toContain('Error invoking remote method') - }) - - // Why 'staged': `aborted` is set only by the bulkUnstage pre-step, which runs for staged entries. - it('unwraps it on the aborted-before-discard path too', async () => { - mocks.runDiscardAllForArea.mockImplementation(async (_area, _paths, handlers) => { - handlers.onError?.(new Error(WRAPPED)) - return { aborted: true, discarded: [], failed: [] } - }) - - await confirmDiscardOf(['a.ts'], 'staged') - - expect(lastDescription()).toBe('index.lock exists') - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control/commit/source-control-discard-editor-owner.test.tsx b/src/renderer/src/components/right-sidebar/source-control/commit/source-control-discard-editor-owner.test.tsx deleted file mode 100644 index e8b12525819..00000000000 --- a/src/renderer/src/components/right-sidebar/source-control/commit/source-control-discard-editor-owner.test.tsx +++ /dev/null @@ -1,101 +0,0 @@ -// @vitest-environment happy-dom -import { act, renderHook } from '@testing-library/react' -import { runtimeTargetForOwnerEnvironment } from '@/runtime/runtime-client-target' -import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target' -import { beforeEach, expect, it, vi } from 'vitest' -import type { EditorPathMutationTarget } from '@/components/editor/autosave/editor-autosave' - -const mocks = vi.hoisted(() => { - const focus: { value: string | null } = { value: null } - return { - focus, - quiesce: vi.fn<(target: EditorPathMutationTarget) => Promise<() => void>>(), - notify: vi.fn<(target: EditorPathMutationTarget) => void>(), - discard: vi.fn(), - bulkDiscard: vi.fn() - } -}) -vi.mock('@/lib/connection-context', () => ({ getConnectionId: () => undefined })) -vi.mock('@/components/editor/autosave/editor-autosave', () => ({ - requestEditorSaveQuiesce: mocks.quiesce, - notifyEditorExternalFileChange: mocks.notify -})) -vi.mock('@/runtime/runtime-git-working-tree-client', () => ({ - discardRuntimeGitPath: mocks.discard, - bulkDiscardRuntimeGitPaths: mocks.bulkDiscard, - stageRuntimeGitPath: vi.fn(), - unstageRuntimeGitPath: vi.fn(), - bulkUnstageRuntimeGitPaths: vi.fn() -})) -vi.mock('@/store', () => ({ - useAppStore: Object.assign(() => undefined, { - getState: () => ({ settings: { activeRuntimeEnvironmentId: mocks.focus.value } }) - }) -})) -import { useSourceControlEntryMutations } from './use-entry-mutations' - -beforeEach(() => vi.clearAllMocks()) - -for (const bulk of [false, true]) { - it.each([ - { name: 'managed repo with local focus', owner: 'host-a', focus: null }, - { name: 'managed repo with another host focused', owner: 'host-a', focus: 'host-b' }, - { name: 'desktop repo with remote focus', owner: null, focus: 'host-b' } - ])( - `${bulk ? 'bulk' : 'single'} discard waits for the $name editor saves`, - async ({ owner, focus }) => { - mocks.focus.value = focus - let release: () => void = () => {} - const releaseHold = (): void => {} - const pendingSave = new Promise<() => void>((resolve) => { - release = () => resolve(releaseHold) - }) - mocks.quiesce.mockImplementation((target) => - target.runtimeEnvironmentId === owner ? pendingSave : Promise.resolve(releaseHold) - ) - const activeRepoTarget: RuntimeClientTarget | null = runtimeTargetForOwnerEnvironment(owner) - const { result } = renderHook(() => - useSourceControlEntryMutations({ - activeRepoTarget, - activeWorktreeId: 'wt-owner', - worktreePath: '/repo', - refreshActiveGitStatusAfterMutation: async () => {} - }) - ) - const paths = bulk ? ['first.txt', 'second.txt'] : ['first.txt'] - let discarded: Promise = Promise.resolve() - await act(async () => { - discarded = bulk - ? result.current.discardMany(paths) - : result.current.discardSingle(paths[0]) - await Promise.resolve() - await Promise.resolve() - }) - const invokedBeforeSaveFinished = (bulk ? mocks.bulkDiscard : mocks.discard).mock.calls.length - release() - await act(async () => { - await discarded - }) - expect(invokedBeforeSaveFinished).toBe(0) - expect(mocks.quiesce.mock.calls.map(([target]) => target)).toEqual( - paths.map((relativePath) => ({ - worktreeId: 'wt-owner', - worktreePath: '/repo', - relativePath, - runtimeEnvironmentId: owner - })) - ) - expect(mocks.notify.mock.calls.map(([target]) => target)).toEqual( - paths.map((relativePath) => ({ - worktreeId: 'wt-owner', - worktreePath: '/repo', - relativePath, - runtimeEnvironmentId: owner - })) - ) - const mutation = bulk ? mocks.bulkDiscard : mocks.discard - expect(mutation).toHaveBeenCalledTimes(1) - expect(mutation.mock.calls[0]?.[0]).toMatchObject({ target: activeRepoTarget }) - } - ) -} diff --git a/src/renderer/src/components/right-sidebar/source-control/listing/source-control-active-open-file-keys.test.ts b/src/renderer/src/components/right-sidebar/source-control/listing/source-control-active-open-file-keys.test.ts deleted file mode 100644 index eed26af6125..00000000000 --- a/src/renderer/src/components/right-sidebar/source-control/listing/source-control-active-open-file-keys.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { GitBranchCompareSummary } from '../../../../../../shared/git/diff/git-diff-compare-types' -import { toBranchCompareSnapshot } from '@/store/slices/editor/git/git-status-reconciliation' -import { buildActiveOpenFileSignature, buildActiveOpenRowKeys } from './active-open-file-keys' - -const branchSummary: GitBranchCompareSummary = { - baseRef: 'main', - baseOid: 'base-1', - compareRef: 'feature', - headOid: 'head-1', - mergeBase: 'merge-1', - changedFiles: 1, - status: 'ready' -} - -describe('buildActiveOpenFileSignature', () => { - it('matches only the current branch comparison, keeping path separators intact', () => { - const path = 'src/a::b.ts' - const signature = buildActiveOpenFileSignature( - 'branch', - path, - toBranchCompareSnapshot(branchSummary), - branchSummary - ) - expect( - buildActiveOpenRowKeys(signature, new Set([`branch::${path}`, `unstaged::${path}`])) - ).toEqual(new Set([`branch::${path}`])) - expect(buildActiveOpenRowKeys(signature, new Set([`unstaged::${path}`])).size).toBe(0) - }) - - it.each(['baseRef', 'baseOid', 'headOid', 'mergeBase'] as const)( - 'does not match an older branch tab when the published %s changes', - (field) => { - expect( - buildActiveOpenFileSignature( - 'branch', - 'src/file.ts', - toBranchCompareSnapshot(branchSummary), - { ...branchSummary, [field]: 'different' } - ) - ).toBeNull() - } - ) - - it('does not claim a branch row without its snapshot or published summary', () => { - expect( - buildActiveOpenFileSignature('branch', 'src/file.ts', undefined, branchSummary) - ).toBeNull() - expect( - buildActiveOpenFileSignature( - 'branch', - 'src/file.ts', - toBranchCompareSnapshot(branchSummary), - null - ) - ).toBeNull() - }) -}) - -describe('buildActiveOpenRowKeys', () => { - it('matches edit tabs to working-tree rows before staged-only fallback', () => { - expect(buildActiveOpenRowKeys('edit::docs/readme.md')).toEqual( - new Set(['unstaged::docs/readme.md', 'untracked::docs/readme.md']) - ) - expect( - buildActiveOpenRowKeys( - 'edit::docs/readme.md', - new Set(['staged::docs/readme.md', 'unstaged::docs/readme.md']) - ) - ).toEqual(new Set(['unstaged::docs/readme.md'])) - expect( - buildActiveOpenRowKeys('edit::docs/readme.md', new Set(['staged::docs/readme.md'])) - ).toEqual(new Set(['staged::docs/readme.md'])) - }) - - it('does not match compare or combined diff tabs to pending rows', () => { - expect( - buildActiveOpenRowKeys('branch::src/file.ts', new Set(['unstaged::src/file.ts'])).size - ).toBe(0) - expect(buildActiveOpenRowKeys('commit::src/file.ts').size).toBe(0) - expect(buildActiveOpenRowKeys('combined-uncommitted::src/file.ts').size).toBe(0) - expect(buildActiveOpenRowKeys('combined-branch::src/file.ts').size).toBe(0) - expect(buildActiveOpenRowKeys('combined-commit::src/file.ts').size).toBe(0) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/stale-conflict-operation-poll.test.tsx b/src/renderer/src/components/right-sidebar/source-control/sync/stale-conflict-operation-poll.test.tsx deleted file mode 100644 index bdd6e3cae48..00000000000 --- a/src/renderer/src/components/right-sidebar/source-control/sync/stale-conflict-operation-poll.test.tsx +++ /dev/null @@ -1,79 +0,0 @@ -// @vitest-environment happy-dom - -import { act, createElement } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { GitConflictOperation } from '../../../../../../shared/git/status/git-status-types' -import { useStaleConflictOperationPolling } from './stale-conflict-operation-poll' - -globalThis.IS_REACT_ACT_ENVIRONMENT = true - -const request = vi.hoisted(() => vi.fn<() => Promise>()) -vi.mock('@/runtime/runtime-git-status-client', () => ({ - getRuntimeGitConflictOperation: request -})) -vi.mock('./worktree-git-owner-target', () => ({ - getWorktreeGitOwnerTarget: () => ({ kind: 'local' }) -})) -vi.mock('@/lib/connection-context', () => ({ getConnectionId: () => undefined })) - -const worktrees = ['one', 'two'].map((name) => ({ - id: `repo::/repo/${name}`, - path: `/repo/${name}`, - repoId: 'repo' -})) -const conflictOperationByWorktree: Record = Object.fromEntries( - worktrees.map(({ id }) => [id, 'merge']) -) -const repoMap = new Map([['repo', { kind: 'git' as const }]]) -const slowTaskBackoff = { idleMultiplier: 1, changeSignalMultiplier: 1, maxIntervalMs: 300_000 } -const setConflictOperation = (): void => {} -const isConnectionReady = (): boolean => true - -function HookProbe({ enabled }: { enabled: boolean }): null { - useStaleConflictOperationPolling({ - enabled, - activeWorktreeId: null, - allWorktrees: worktrees, - repoMap, - conflictOperationByWorktree, - setConflictOperation, - isConnectionReady, - slowTaskBackoff - }) - return null -} - -describe('useStaleConflictOperationPolling', () => { - let root: Root - let container: HTMLDivElement - - beforeEach(() => { - vi.useFakeTimers() - vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible') - request.mockReset() - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - }) - - afterEach(async () => { - await act(async () => root.unmount()) - container.remove() - vi.restoreAllMocks() - vi.useRealTimers() - }) - - it('stops probing remaining worktrees once the effect is retired and the probe rejects', async () => { - const pending = Promise.withResolvers() - request.mockReturnValueOnce(pending.promise) - await act(async () => root.render(createElement(HookProbe, { enabled: true }))) - expect(request).toHaveBeenCalledTimes(1) - - await act(async () => root.render(createElement(HookProbe, { enabled: false }))) - await act(async () => pending.reject(new Error('Disconnected during probe'))) - await act(async () => vi.advanceTimersByTimeAsync(10_000)) - - expect(request).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/renderer/src/components/sidebar/project-admission/dialog/AddRepoDialogChrome.test.tsx b/src/renderer/src/components/sidebar/project-admission/dialog/AddRepoDialogChrome.test.tsx index 6edef4bdfa9..f4f6d8965f9 100644 --- a/src/renderer/src/components/sidebar/project-admission/dialog/AddRepoDialogChrome.test.tsx +++ b/src/renderer/src/components/sidebar/project-admission/dialog/AddRepoDialogChrome.test.tsx @@ -44,17 +44,6 @@ function backdrop(): Element { } describe('AddRepoDialogChrome dismissal', () => { - it('keeps an in-flight clone open after a backdrop click', async () => { - const user = userEvent.setup() - const onOpenChange = vi.fn() - render() - - await user.click(backdrop()) - - expect(onOpenChange).not.toHaveBeenCalled() - expect(screen.queryByRole('dialog', { name: 'Clone from URL' })).not.toBeNull() - }) - it('allows backdrop dismissal after the clone settles', async () => { const user = userEvent.setup() const onOpenChange = vi.fn() @@ -68,20 +57,4 @@ describe('AddRepoDialogChrome dismissal', () => { expect(onOpenChange).toHaveBeenCalledWith(false) expect(screen.queryByRole('dialog', { name: 'Clone from URL' })).toBeNull() }) - - it.each(['Escape', 'Close'])( - 'keeps explicit %s dismissal available during a clone', - async (action) => { - const user = userEvent.setup() - const onOpenChange = vi.fn() - render() - - await (action === 'Escape' - ? user.keyboard('{Escape}') - : user.click(screen.getByRole('button', { name: 'Close' }))) - - expect(onOpenChange).toHaveBeenCalledWith(false) - expect(screen.queryByRole('dialog', { name: 'Clone from URL' })).toBeNull() - } - ) }) diff --git a/src/renderer/src/components/sidebar/project-admission/nested-import/AddRepoNestedImportStep.test.tsx b/src/renderer/src/components/sidebar/project-admission/nested-import/AddRepoNestedImportStep.test.tsx deleted file mode 100644 index 52f48791564..00000000000 --- a/src/renderer/src/components/sidebar/project-admission/nested-import/AddRepoNestedImportStep.test.tsx +++ /dev/null @@ -1,129 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' - -import { createRoot, type Root } from 'react-dom/client' - -import { afterEach, describe, expect, it, vi } from 'vitest' -import { AddRepoNestedImportStep } from './AddRepoNestedImportStep' -import { TooltipProvider } from '@/components/ui/tooltip' -import { Dialog } from '@/components/ui/dialog' -import type { NestedRepoScanResult } from '../../../../../../shared/project-group-types' - -const scan: NestedRepoScanResult = { - selectedPath: '/workspace/platform', - selectedPathKind: 'non_git_folder', - repos: [ - { path: '/workspace/platform/web', displayName: 'web', depth: 1 }, - { path: '/workspace/platform/payments/api', displayName: 'api', depth: 2 }, - { path: '/workspace/platform/billing/api', displayName: 'api', depth: 2 } - ], - truncated: false, - timedOut: false, - stopped: false, - durationMs: 4, - maxDepth: 3, - maxRepos: 100, - timeoutMs: null -} - -function findButton(container: HTMLElement, label: string): HTMLButtonElement { - const button = Array.from(container.querySelectorAll('button')).find((entry) => - entry.textContent?.includes(label) - ) - if (!button) { - throw new Error(`Button not found: ${label}`) - } - return button -} - -describe('AddRepoNestedImportStep', () => { - let root: Root | null = null - let container: HTMLDivElement | null = null - - afterEach(() => { - if (root) { - act(() => root?.unmount()) - root = null - } - container?.remove() - container = null - }) - - it('maps the group choice to grouped import and the separate choice to separate import', () => { - const onImport = vi.fn() - const host = document.createElement('div') - container = host - document.body.appendChild(host) - root = createRoot(host) - - act(() => { - root?.render( - - - repo.path))} - isAdding={false} - scanInProgress={false} - onGroupNameChange={vi.fn()} - onSelectedPathsChange={vi.fn()} - onImport={onImport} - onOpenAsFolder={vi.fn()} - onStopScan={vi.fn()} - /> - - - ) - }) - - act(() => { - findButton(host, 'Yes, import as group').click() - findButton(host, 'No, import separately').click() - }) - - expect(onImport).toHaveBeenNthCalledWith(1, 'group') - expect(onImport).toHaveBeenNthCalledWith(2, 'separate') - }) - - it('offers opening the parent folder when no repositories are selected', () => { - const onOpenAsFolder = vi.fn() - const host = document.createElement('div') - container = host - document.body.appendChild(host) - root = createRoot(host) - - act(() => { - root?.render( - - - - - - ) - }) - - expect(host.textContent).toContain('No repositories are selected') - expect(findButton(host, 'No, import separately').disabled).toBe(true) - expect(findButton(host, 'Yes, import as group').disabled).toBe(true) - expect(findButton(host, 'Open as Folder').disabled).toBe(false) - - act(() => { - findButton(host, 'Open as Folder').click() - }) - - expect(onOpenAsFolder).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/renderer/src/components/sidebar/sidebar-feedback/use-sidebar-feedback-images.test.tsx b/src/renderer/src/components/sidebar/sidebar-feedback/use-sidebar-feedback-images.test.tsx deleted file mode 100644 index 5b93c545cd2..00000000000 --- a/src/renderer/src/components/sidebar/sidebar-feedback/use-sidebar-feedback-images.test.tsx +++ /dev/null @@ -1,119 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { FeedbackImageDraft } from '@/lib/feedback-image-attachments' - -import { useSidebarFeedbackImages } from './use-sidebar-feedback-images' - -const { readFeedbackImageFiles } = vi.hoisted(() => ({ readFeedbackImageFiles: vi.fn() })) - -vi.mock('@/lib/feedback-image-attachments', async (importOriginal) => ({ - ...(await importOriginal>()), - readFeedbackImageFiles -})) - -vi.mock('sonner', () => ({ toast: { info: vi.fn(), warning: vi.fn(), error: vi.fn() } })) - -type HookResult = ReturnType - -let container: HTMLDivElement -let root: Root -let latest: HookResult | undefined -let mountedRef: { current: boolean } - -function Harness(): null { - latest = useSidebarFeedbackImages({ - open: false, - isSubmitting: false, - mountedRef - }) - return null -} - -function draft(id: string, bytes: number): FeedbackImageDraft { - return { - id, - name: `${id}.png`, - contentType: 'image/png', - bytes, - data: new Uint8Array([1]), - previewUrl: `blob:${id}` - } -} - -beforeEach(() => { - readFeedbackImageFiles.mockReset() - URL.revokeObjectURL = vi.fn() - mountedRef = { current: true } - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - act(() => { - root.render() - }) -}) - -afterEach(() => { - act(() => { - root.unmount() - }) - container.remove() - latest = undefined -}) - -describe('useSidebarFeedbackImages', () => { - it('counts a just-read batch when another add lands before the re-render', async () => { - let finishFirstRead: ((value: unknown) => void) | undefined - readFeedbackImageFiles.mockReturnValueOnce( - new Promise((resolve) => { - finishFirstRead = resolve - }) - ) - readFeedbackImageFiles.mockReturnValue(new Promise(() => {})) - const first = new File(['x'], 'first.png', { type: 'image/png' }) - const second = new File(['x'], 'second.png', { type: 'image/png' }) - const firstBytes = 3 * 1024 * 1024 - - act(() => { - latest!.handleAddFiles([first]) - }) - - await act(async () => { - finishFirstRead?.({ images: [draft('first', firstBytes)], errors: [], notices: [] }) - await Promise.resolve() - await Promise.resolve() - // Still inside act: the first batch has committed to the ref, not to state. - expect(latest!.images).toEqual([]) - latest!.handleAddFiles([second]) - }) - - expect(readFeedbackImageFiles).toHaveBeenNthCalledWith(2, [second], 1, firstBytes) - }) - - it('sizes a later add against the shrunk size, not the raw file size', async () => { - let finishShrink: ((value: unknown) => void) | undefined - readFeedbackImageFiles.mockReturnValueOnce( - new Promise((resolve) => { - finishShrink = resolve - }) - ) - readFeedbackImageFiles.mockReturnValue(new Promise(() => {})) - const retina = new File(['x'], 'retina.png', { type: 'image/png' }) - Object.defineProperty(retina, 'size', { value: 6_400_000 }) - const second = new File(['x'], 'second.png', { type: 'image/png' }) - - await act(async () => { - latest!.handleAddFiles([retina]) - latest!.handleAddFiles([second]) - }) - expect(readFeedbackImageFiles).toHaveBeenCalledTimes(1) - - await act(async () => { - finishShrink?.({ images: [draft('retina', 1_750_000)], errors: [], notices: [] }) - }) - - expect(readFeedbackImageFiles).toHaveBeenNthCalledWith(2, [second], 1, 1_750_000) - }) -}) diff --git a/src/renderer/src/components/sidebar/workspace-actions/deletion/DeleteWorktreeDialogFooter.test.tsx b/src/renderer/src/components/sidebar/workspace-actions/deletion/DeleteWorktreeDialogFooter.test.tsx deleted file mode 100644 index b98c480aec6..00000000000 --- a/src/renderer/src/components/sidebar/workspace-actions/deletion/DeleteWorktreeDialogFooter.test.tsx +++ /dev/null @@ -1,111 +0,0 @@ -// @vitest-environment happy-dom - -import { act, createRef } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, expect, it, vi } from 'vitest' -import { toast } from 'sonner' -import { TooltipProvider } from '../../../ui/tooltip' -import { DeleteWorktreeDialogFooter } from './DeleteWorktreeDialogFooter' - -const savePreference = vi.hoisted(() => vi.fn()) -vi.mock('@/store', () => ({ - useAppStore: { getState: () => ({ updateSettingsOrThrow: savePreference }) } -})) -vi.mock('sonner', () => ({ toast: { error: vi.fn(), dismiss: vi.fn() } })) -let root: Root | undefined - -function renderFooter(disabled = false) { - const container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - const onForceDelete = vi.fn() - const onSavingChange = vi.fn() - const confirmButtonRef = createRef() - act(() => - root?.render( - - - - ) - ) - return { container, onForceDelete, onSavingChange, confirmButtonRef } -} - -async function selectPreference(container: HTMLElement) { - await act(async () => { - container - .querySelector('button[aria-label="More force delete options"]') - ?.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true })) - }) - const item = document.querySelector('[role="menuitem"]') - if (!(item instanceof HTMLElement)) { - throw new Error('Missing preference option') - } - await act(async () => item.click()) -} - -afterEach(() => { - act(() => root?.unmount()) - root = undefined - document.body.innerHTML = '' - vi.clearAllMocks() -}) - -it('keeps the primary button focused, full size, and a one-time delete', async () => { - const { confirmButtonRef, onForceDelete } = renderFooter() - expect(confirmButtonRef.current?.dataset.size).toBe('default') - expect(confirmButtonRef.current?.textContent).toBe('Force Delete') - await act(async () => confirmButtonRef.current?.click()) - expect(onForceDelete).toHaveBeenCalledOnce() - expect(savePreference).not.toHaveBeenCalled() - expect(toast.dismiss).not.toHaveBeenCalled() -}) - -it('saves the shared preference before retrying and exposes the pending state', async () => { - let finish: (() => void) | undefined - savePreference.mockImplementation( - () => - new Promise((resolve) => { - finish = resolve - }) - ) - const { container, onForceDelete, onSavingChange } = renderFooter() - await selectPreference(container) - expect(savePreference).toHaveBeenCalledWith({ alwaysForceDeleteWorktrees: true }) - expect(onForceDelete).not.toHaveBeenCalled() - expect(onSavingChange).toHaveBeenLastCalledWith(true) - expect(container.querySelectorAll('button:disabled')).toHaveLength(2) - await act(async () => finish?.()) - expect(onSavingChange).toHaveBeenLastCalledWith(false) - expect(onForceDelete).toHaveBeenCalledOnce() -}) - -it('leaves the recovery action available when saving fails', async () => { - savePreference.mockRejectedValue(new Error('Disk full')) - const { container, onForceDelete, onSavingChange } = renderFooter() - await selectPreference(container) - expect(onForceDelete).not.toHaveBeenCalled() - expect(onSavingChange).toHaveBeenLastCalledWith(false) - expect(container.querySelectorAll('button:disabled')).toHaveLength(0) - expect(toast.error).toHaveBeenCalledWith('Could not save deletion preference', { - description: 'Disk full' - }) -}) - -it('disables both retry choices while deletion is in progress', () => { - const { container } = renderFooter(true) - expect(container.querySelectorAll('button:disabled')).toHaveLength(3) -}) diff --git a/src/renderer/src/components/sidebar/workspace-actions/deletion/delete-worktree-failure-toast.test.tsx b/src/renderer/src/components/sidebar/workspace-actions/deletion/delete-worktree-failure-toast.test.tsx deleted file mode 100644 index 07c2ffca3b0..00000000000 --- a/src/renderer/src/components/sidebar/workspace-actions/deletion/delete-worktree-failure-toast.test.tsx +++ /dev/null @@ -1,121 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { toast } from 'sonner' -import { showDeleteWorktreeFailureToast } from './delete-worktree-failure-toast' - -vi.mock('sonner', () => ({ - toast: { - error: vi.fn(), - info: vi.fn(), - dismiss: vi.fn() - } -})) - -const mountedRoots: Root[] = [] - -function renderToastBody(method: 'error' | 'info'): HTMLElement { - const description = vi.mocked(toast[method]).mock.calls.at(-1)?.[1] - ?.description as React.ReactElement - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - mountedRoots.push(root) - act(() => { - root.render(description) - }) - return container -} - -function clickButton(container: HTMLElement, label: string): void { - const button = [...container.querySelectorAll('button')].find( - (el) => el.textContent?.trim() === label - ) - if (!button) { - throw new Error(`button "${label}" not found`) - } - act(() => { - button.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) -} - -afterEach(() => { - mountedRoots.splice(0).forEach((root) => act(() => root.unmount())) - document.body.innerHTML = '' - vi.clearAllMocks() -}) - -describe('showDeleteWorktreeFailureToast', () => { - it('uses a persistent in-body action footer when force delete is available', () => { - const onViewChanges = vi.fn() - const onForceDelete = vi.fn() - const onDeleteAnyway = vi.fn() - - showDeleteWorktreeFailureToast({ - error: 'branch has changes', - canForceDelete: true, - forceDeleteReason: 'dirty', - onViewChanges, - onForceDelete, - onDeleteAnyway, - worktreeId: 'wt-1', - worktreeName: 'feature/foo' - }) - - expect(toast.info).toHaveBeenCalledWith( - 'Failed to delete workspace feature/foo', - expect.objectContaining({ - id: 'delete-worktree-failure:|wt-1', - dismissible: true, - duration: Infinity - }) - ) - const options = vi.mocked(toast.info).mock.calls.at(-1)?.[1] as - | { action?: unknown; cancel?: unknown } - | undefined - expect(options?.action).toBeUndefined() - expect(options?.cancel).toBeUndefined() - - const body = renderToastBody('info') - expect(body.textContent).toContain('It has changed files.') - - clickButton(body, 'View') - expect(toast.dismiss).toHaveBeenCalledWith('delete-worktree-failure:|wt-1') - expect(onViewChanges).toHaveBeenCalled() - - clickButton(body, 'Force Delete') - expect(toast.dismiss).toHaveBeenCalledWith('delete-worktree-failure:|wt-1') - expect(onForceDelete).toHaveBeenCalled() - }) - - it('offers Delete Anyway when the archive hook refused the removal', () => { - const onDeleteAnyway = vi.fn() - - showDeleteWorktreeFailureToast({ - error: 'Archive hook failed for worktree: /w/feature — exited 23.', - canForceDelete: false, - forceDeleteReason: null, - canWaiveArchiveHook: true, - onViewChanges: vi.fn(), - onForceDelete: vi.fn(), - onDeleteAnyway, - worktreeId: 'wt-archive', - worktreeName: 'feature/archive' - }) - - expect(toast.error).toHaveBeenCalledWith( - 'Failed to delete workspace feature/archive', - expect.objectContaining({ duration: Infinity }) - ) - - const body = renderToastBody('error') - expect(body.textContent).toContain('Delete Anyway') - expect(body.textContent).not.toContain('Force Delete') - - clickButton(body, 'Delete Anyway') - expect(toast.dismiss).toHaveBeenCalledWith('delete-worktree-failure:|wt-archive') - expect(onDeleteAnyway).toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/sidebar/workspace-actions/deletion/folder-workspace-delete.test.ts b/src/renderer/src/components/sidebar/workspace-actions/deletion/folder-workspace-delete.test.ts deleted file mode 100644 index e181f361f77..00000000000 --- a/src/renderer/src/components/sidebar/workspace-actions/deletion/folder-workspace-delete.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { AppState } from '@/store' -import { deleteFolderWorkspaceUnlessUnsaved } from './folder-workspace-delete' -import { projectRemovalTargets } from './removal-unsaved-files' - -const mocks = vi.hoisted(() => ({ toastError: vi.fn() })) - -vi.mock('sonner', () => ({ toast: { error: mocks.toastError } })) -vi.mock('@/components/editor/model-lifetime/identity/editor-model-owner', () => ({ - resolveEditorModelOwner: () => ({ environmentId: null, hostId: 'local' }), - getEditorModelOwnerKey: () => '' -})) - -function state(dirty: boolean): AppState { - const openFiles = dirty - ? [ - { - id: 'f', - filePath: '/notes/a.md', - relativePath: 'a.md', - worktreeId: 'folder:notes', - language: 'markdown', - isDirty: true, - mode: 'edit' - } - ] - : [] - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the delete and the unsaved check read only these fields. - return { - openFiles, - editorDrafts: {}, - editorBufferIdOf: { f: 'f' }, - editorBufferViews: { f: ['f'] }, - worktreesByRepo: {}, - detectedWorktreesByRepo: {}, - projectGroups: [], - folderWorkspaces: [{ id: 'notes', name: 'Notes' }], - activeWorktreeId: 'folder:notes', - activeWorkspaceExecutionHostId: null, - deleteFolderWorkspace: vi.fn().mockResolvedValue(true), - setActiveWorktree: vi.fn() - } as unknown as AppState -} - -describe('deleteFolderWorkspaceUnlessUnsaved', () => { - beforeEach(() => { - mocks.toastError.mockClear() - }) - - it('refuses while the workspace holds unsaved editor text, and says so', () => { - const s = state(true) - expect(deleteFolderWorkspaceUnlessUnsaved(() => s, 'notes')).toBeNull() - expect(s.deleteFolderWorkspace).not.toHaveBeenCalled() - expect(mocks.toastError).toHaveBeenCalledWith('Save or close 1 unsaved file in Notes first') - }) - - it('deletes without asking when a same-id folder on another host keeps the tabs open', async () => { - const s = state(true) - Object.assign(s, { - folderWorkspaces: [ - { id: 'notes', name: 'Notes', executionHostId: 'local' }, - { id: 'notes', name: 'Notes', executionHostId: 'ssh:box' } - ] - }) - await expect(deleteFolderWorkspaceUnlessUnsaved(() => s, 'notes', 'ssh:box')).resolves.toBe( - true - ) - expect(mocks.toastError).not.toHaveBeenCalled() - }) - - it('deletes and clears the selection when it was the active workspace', async () => { - const s = state(false) - await expect(deleteFolderWorkspaceUnlessUnsaved(() => s, 'notes')).resolves.toBe(true) - expect(s.deleteFolderWorkspace).toHaveBeenCalledWith('notes', undefined) - expect(s.setActiveWorktree).toHaveBeenCalledWith(null) - }) -}) - -describe('projectRemovalTargets', () => { - it('names every row of the project on the removed host', () => { - const rows = { - detectedWorktreesByRepo: { - repo: { worktrees: [{ id: 'repo::/detected', hostId: 'ssh:box' }] } - }, - worktreesByRepo: { - repo: [ - { id: 'repo::/a', hostId: 'ssh:box' }, - { id: 'repo::/b', hostId: 'local' }, - { id: 'repo::/c' } - ] - } - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only id and hostId are read. - const s = rows as unknown as Pick - expect(projectRemovalTargets(s, [{ repoId: 'repo', hostId: 'ssh:box' }])).toEqual([ - { id: 'repo::/a', hostId: 'ssh:box' }, - { id: 'repo::/detected', hostId: 'ssh:box' } - ]) - }) -}) diff --git a/src/renderer/src/components/sidebar/workspace-actions/deletion/preserved-branch-toast.test.tsx b/src/renderer/src/components/sidebar/workspace-actions/deletion/preserved-branch-toast.test.tsx deleted file mode 100644 index 7bf54ff87f8..00000000000 --- a/src/renderer/src/components/sidebar/workspace-actions/deletion/preserved-branch-toast.test.tsx +++ /dev/null @@ -1,132 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { toast } from 'sonner' -import { TooltipProvider } from '../../../ui/tooltip' -import type { RemoveWorktreeResult } from '../../../../../../shared/worktree/create-types' -import { showPreservedBranchToast } from './preserved-branch-toast' - -vi.mock('sonner', () => ({ - toast: { - warning: vi.fn(), - dismiss: vi.fn(), - error: vi.fn() - } -})) - -const mountedRoots: Root[] = [] - -function renderToastBody(): HTMLElement { - const description = vi.mocked(toast.warning).mock.calls.at(-1)?.[1] - ?.description as React.ReactElement - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - mountedRoots.push(root) - act(() => { - root.render({description}) - }) - return container -} - -function clickButton(container: HTMLElement, label: string): void { - const button = [...container.querySelectorAll('button')].find( - (el) => el.textContent?.trim() === label - ) - if (!button) { - throw new Error(`button "${label}" not found`) - } - act(() => { - button.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) -} - -afterEach(() => { - mountedRoots.splice(0).forEach((root) => act(() => root.unmount())) - document.body.innerHTML = '' - vi.clearAllMocks() -}) - -describe('showPreservedBranchToast', () => { - it('renders the branch recovery action below the long description', () => { - const onForceDelete = vi.fn() - const result: RemoveWorktreeResult = { - preservedBranch: { - branchName: 'feat/notes-send-any-running-agent', - head: 'abc123' - } - } - - showPreservedBranchToast( - result, - { - displayName: 'Send review notes to any running agent of a worktree', - isMainWorktree: false - }, - onForceDelete - ) - const body = renderToastBody() - - expect(toast.warning).toHaveBeenCalledWith( - 'Worktree deleted, branch kept', - expect.objectContaining({ - id: 'preserved-branch:feat/notes-send-any-running-agent:abc123', - dismissible: true, - duration: Infinity - }) - ) - expect(body.textContent).toContain('feat/notes-send-any-running-agent') - expect(body.textContent).toContain('Send review notes to any running agent of a worktree') - - clickButton(body, 'Force Delete Branch') - - expect(onForceDelete).toHaveBeenCalledWith('feat/notes-send-any-running-agent', 'abc123') - expect(toast.dismiss).toHaveBeenCalledWith( - 'preserved-branch:feat/notes-send-any-running-agent:abc123' - ) - }) - - it('does not show the force-delete action without the preserved head', () => { - const result: RemoveWorktreeResult = { - preservedBranch: { - branchName: 'feature/test' - } - } - - showPreservedBranchToast(result, undefined, vi.fn()) - const body = renderToastBody() - - expect(body.textContent).not.toContain('Force Delete Branch') - expect(toast.warning).toHaveBeenCalledWith( - 'Worktree deleted, branch kept', - expect.not.objectContaining({ duration: Infinity }) - ) - }) - - it('keeps the branch and toast when saving the future choice fails', async () => { - const savePreference = vi.fn().mockRejectedValue(new Error('disk full')) - const onForceDelete = vi.fn() - showPreservedBranchToast( - { preservedBranch: { branchName: 'feature/test', head: 'abc123' } }, - undefined, - onForceDelete, - savePreference - ) - const body = renderToastBody() - await act(async () => { - body - .querySelector('button[aria-label="More branch delete options"]') - ?.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true })) - }) - await act(async () => { - document - .querySelector('[role="menuitem"]') - ?.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) - - expect(onForceDelete).not.toHaveBeenCalled() - expect(toast.dismiss).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/sidebar/workspace-board/drag/use-workspace-kanban-card-pointer-drag.test.ts b/src/renderer/src/components/sidebar/workspace-board/drag/use-workspace-kanban-card-pointer-drag.test.ts deleted file mode 100644 index b7d9939f9f4..00000000000 --- a/src/renderer/src/components/sidebar/workspace-board/drag/use-workspace-kanban-card-pointer-drag.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { describe, expect, it } from 'vitest' -import './use-workspace-kanban-card-pointer-drag' -import { resolveWorkspaceKanbanPointerDragSelection } from './workspace-kanban-pointer-drag-selection' -import { shouldStartWorkspaceKanbanCardPointerDrag } from './workspace-kanban-card-pointer-drag-start' -import { makeWorktree } from '../../../../store/slices/worktrees-slice-test-fixtures' - -function pointerEvent(overrides: Partial = {}): PointerEvent { - return { - button: 0, - ctrlKey: false, - metaKey: false, - pointerType: 'mouse', - shiftKey: false, - ...overrides - } as PointerEvent -} - -describe('workspace kanban card pointer drag start', () => { - it('starts for plain primary mouse drags', () => { - expect(shouldStartWorkspaceKanbanCardPointerDrag(pointerEvent())).toBe(true) - }) - - it('does not steal modifier gestures from selection', () => { - expect(shouldStartWorkspaceKanbanCardPointerDrag(pointerEvent({ metaKey: true }))).toBe(false) - expect(shouldStartWorkspaceKanbanCardPointerDrag(pointerEvent({ ctrlKey: true }))).toBe(false) - expect(shouldStartWorkspaceKanbanCardPointerDrag(pointerEvent({ shiftKey: true }))).toBe(false) - }) - - it('ignores touch and non-primary buttons', () => { - expect(shouldStartWorkspaceKanbanCardPointerDrag(pointerEvent({ pointerType: 'touch' }))).toBe( - false - ) - expect(shouldStartWorkspaceKanbanCardPointerDrag(pointerEvent({ button: 1 }))).toBe(false) - }) -}) - -describe('workspace kanban pointer drag selection identity', () => { - it('does not expand a same-id drag to the unselected host', () => { - const local = makeWorktree({ id: 'shared', repoId: 'repo', hostId: 'local' }) - const remote = makeWorktree({ id: 'shared', repoId: 'repo', hostId: 'ssh:host-b' }) - - expect( - resolveWorkspaceKanbanPointerDragSelection({ - sourceWorktreeId: remote.id, - sourceWorktreeIdentity: 'ssh:host-b|shared', - selectedWorktreeIds: new Set(['local|shared']), - selectedWorktrees: [local] - }) - ).toEqual({ - worktreeIds: ['shared'], - worktreeIdentities: ['ssh:host-b|shared'], - worktreeKeys: ['ssh:host-b|shared'] - }) - }) - - it('drags the selected host-qualified batch when the source row is selected', () => { - const local = makeWorktree({ id: 'shared', repoId: 'repo', hostId: 'local' }) - const remote = makeWorktree({ id: 'shared', repoId: 'repo', hostId: 'ssh:host-b' }) - - expect( - resolveWorkspaceKanbanPointerDragSelection({ - sourceWorktreeId: remote.id, - sourceWorktreeIdentity: 'ssh:host-b|shared', - selectedWorktreeIds: new Set(['local|shared', 'ssh:host-b|shared']), - selectedWorktrees: [local, remote] - }) - ).toEqual({ - worktreeIds: ['shared', 'shared'], - worktreeIdentities: ['local|shared', 'ssh:host-b|shared'], - worktreeKeys: ['local|shared', 'ssh:host-b|shared'] - }) - }) -}) diff --git a/src/renderer/src/components/sidebar/workspace-board/drag/workspace-board-host-column-drops.test.tsx b/src/renderer/src/components/sidebar/workspace-board/drag/workspace-board-host-column-drops.test.tsx deleted file mode 100644 index f5f725df063..00000000000 --- a/src/renderer/src/components/sidebar/workspace-board/drag/workspace-board-host-column-drops.test.tsx +++ /dev/null @@ -1,91 +0,0 @@ -// @vitest-environment happy-dom - -import { cleanup, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' -import type { AppState } from '@/store/types' -import { makeWorktree } from '@/store/slices/worktrees-slice-test-fixtures' -import { toRuntimeExecutionHostId } from '../../../../../../shared/execution-host' -import { useWorkspaceKanbanWorktreeActions } from '../surface/use-workspace-kanban-worktree-actions' -import { useWorktreeStatusMutations } from '../../worktree-list/drag/use-status-mutations' -import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity' - -const local = makeWorktree({ id: 'repo::/local', repoId: 'repo', path: '/local' }) -const hosted = makeWorktree({ - id: 'repo::/hosted', - repoId: 'repo', - path: '/hosted', - hostId: toRuntimeExecutionHostId('env-1') -}) -const catalog = { - orderedKeys: [getWorktreeHostIdentity(local), getWorktreeHostIdentity(hosted)], - rankByKey: new Map() -} - -let updateWorktreesMeta: ReturnType> - -beforeEach(() => { - updateWorktreesMeta = vi.fn(() => Promise.resolve()) - useAppStore.setState({ - worktreesByRepo: { repo: [local, hosted] }, - folderWorkspaces: [], - workspaceStatuses: [{ id: 'in-progress', label: 'In progress' }], - hostWorkspaceStatuses: { 'env-1': [{ id: 'status-6', label: 'Today' }] }, - removedRuntimeEnvironmentIds: new Set(), - updateWorktreesMeta, - recordFeatureInteraction: vi.fn() - }) -}) - -afterEach(cleanup) - -describe("drops into a paired host's own column", () => { - it('board: moves only the host card and leaves the local card unranked', () => { - const { result } = renderHook(() => - useWorkspaceKanbanWorktreeActions({ - boardDragGroups: [], - laneFullWorktreeIds: new Map(), - laneViews: new Map(), - maybeSyncTaskStatuses: vi.fn(), - sortBy: 'manual', - updateWorktreeMeta: vi.fn(), - updateWorktreesMeta, - workspaceStatuses: [{ id: 'in-progress', label: 'In progress' }], - worktreeById: new Map([ - [local.id, local], - [hosted.id, hosted] - ]), - worktreeByKey: new Map([local, hosted].map((row) => [getWorktreeHostIdentity(row), row])), - manualOrderCatalog: catalog, - worktreesByStatus: new Map() - }) - ) - - result.current.dropWorktreesAtEndOfStatus([local.id], 'status-6') - expect(updateWorktreesMeta).not.toHaveBeenCalled() - - result.current.dropWorktreesAtEndOfStatus([local.id, hosted.id], 'status-6') - expect(updateWorktreesMeta.mock.calls[0]?.[0].map((entry) => entry.worktreeId)).toEqual([ - hosted.id - ]) - }) - - it('sidebar: ignores a local card dropped into the host-only group', () => { - const { result } = renderHook(() => - useWorktreeStatusMutations({ - manualOrderCatalog: catalog, - workspaceStatuses: [{ id: 'in-progress', label: 'In progress' }], - sortBy: 'manual' - }) - ) - - result.current.moveWorktreesToStatusAtIndex({ - worktreeIds: [local.id], - status: 'status-6', - dropIndex: 0, - groups: [] - }) - - expect(updateWorktreesMeta).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/sidebar/workspace-board/surface/use-visible-workspace-kanban-worktree-ids.test.tsx b/src/renderer/src/components/sidebar/workspace-board/surface/use-visible-workspace-kanban-worktree-ids.test.tsx deleted file mode 100644 index d6b05ca79f5..00000000000 --- a/src/renderer/src/components/sidebar/workspace-board/surface/use-visible-workspace-kanban-worktree-ids.test.tsx +++ /dev/null @@ -1,78 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { cleanup, renderHook } from '@testing-library/react' -import { useAppStore } from '@/store' -import { structuredAgentSessionPaneKey } from '../../../../../../shared/agent-session/view/structured-agent-session-projection' -import type { Tab } from '../../../../../../shared/tab-types' -import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity' -import { makeRepo, makeWorktree } from '../../../worktree-jump/worktree-jump-palette-test-fixtures' -import { useVisibleWorkspaceKanbanWorktreeIds } from './use-visible-workspace-kanban-worktree-ids' - -const initialState = useAppStore.getInitialState() - -describe('useVisibleWorkspaceKanbanWorktreeIds', () => { - beforeEach(() => { - useAppStore.setState(initialState, true) - }) - - afterEach(() => { - cleanup() - useAppStore.setState(initialState, true) - }) - - it('keeps a single-host filter host-qualified when workspace ids collide', () => { - const local = makeWorktree('shared', 'Local workspace', { hostId: 'local' }) - const ssh = makeWorktree('shared', 'SSH workspace', { hostId: 'ssh:box' }) - const repo = makeRepo() - useAppStore.setState({ - worktreesByRepo: { [repo.id]: [local, ssh] }, - showSleepingWorkspaces: true, - visibleWorkspaceHostIds: ['local'] - }) - - const { result } = renderHook(() => - useVisibleWorkspaceKanbanWorktreeIds({ - allWorktrees: [local, ssh], - repoMap: new Map([[repo.id, repo]]) - }) - ) - - expect(result.current).toEqual(new Set([getWorktreeHostIdentity(local)])) - }) - - it('keeps a structured-chat workspace visible when sleeping workspaces are hidden', () => { - const worktree = makeWorktree('chat', 'Chat workspace') - const repo = makeRepo() - const structuredTab: Tab = { - id: 'chat-tab', - entityId: 'chat-session', - groupId: 'chat-group', - worktreeId: worktree.id, - contentType: 'agent-session', - agentSessionAgent: 'codex', - label: 'Chat', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 0 - } - useAppStore.setState({ - worktreesByRepo: { [repo.id]: [worktree] }, - unifiedTabsByWorktree: { [worktree.id]: [structuredTab] }, - structuredChatSleptAtByPaneKey: { - [structuredAgentSessionPaneKey(structuredTab.id, structuredTab.entityId)]: null - }, - showSleepingWorkspaces: false - }) - - const { result } = renderHook(() => - useVisibleWorkspaceKanbanWorktreeIds({ - allWorktrees: [worktree], - repoMap: new Map([[repo.id, repo]]) - }) - ) - - expect(result.current).toEqual(new Set([getWorktreeHostIdentity(worktree)])) - }) -}) diff --git a/src/renderer/src/components/sidebar/workspace-board/viewport/workspace-kanban-virtual-lane-layout.test.ts b/src/renderer/src/components/sidebar/workspace-board/viewport/workspace-kanban-virtual-lane-layout.test.ts deleted file mode 100644 index 8835912a598..00000000000 --- a/src/renderer/src/components/sidebar/workspace-board/viewport/workspace-kanban-virtual-lane-layout.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getAreaSelectionCardRects } from '../selection/workspace-kanban-area-selection-card-rects' -import { getAreaSelectionCardIds } from '../selection/workspace-kanban-area-selection-dom' -import { - getWorkspaceKanbanVirtualLaneItemRects, - registerWorkspaceKanbanVirtualLaneLayout, - resolveWorkspaceKanbanVirtualLaneDropIndex, - resolveWorkspaceKanbanVirtualLaneDropIndicatorY -} from './workspace-kanban-virtual-lane-layout' - -const ITEM_COUNT = 102 -const ITEM_STRIDE = 44 -const ITEM_HEIGHT = 36 - -function createLayoutElements(): { - scrollElement: HTMLElement - spacerElement: HTMLElement -} { - const scrollElement = { - scrollTop: 0, - getBoundingClientRect: () => ({ - left: 20, - top: 100, - right: 220, - bottom: 600, - width: 200, - height: 500 - }) - } as unknown as HTMLElement - const spacerElement = { - getBoundingClientRect: () => ({ - left: 26, - top: 108 - scrollElement.scrollTop, - right: 214, - bottom: 108 - scrollElement.scrollTop + ITEM_COUNT * ITEM_STRIDE, - width: 188, - height: ITEM_COUNT * ITEM_STRIDE - }) - } as unknown as HTMLElement - return { scrollElement, spacerElement } -} - -function registerLayout(scrollElement: HTMLElement, spacerElement: HTMLElement): () => void { - return registerWorkspaceKanbanVirtualLaneLayout({ - scrollElement, - spacerElement, - getItemIds: () => Array.from({ length: ITEM_COUNT }, (_, index) => `w${index}`), - getMeasurements: () => - Array.from({ length: ITEM_COUNT }, (_, index) => ({ - index, - start: index * ITEM_STRIDE, - end: index * ITEM_STRIDE + ITEM_HEIGHT - })) - }) -} - -describe('workspace kanban virtual lane layout', () => { - it('resolves mid-lane and bottom drops immediately after a large scroll jump', () => { - const { scrollElement, spacerElement } = createLayoutElements() - const unregister = registerLayout(scrollElement, spacerElement) - scrollElement.scrollTop = 3_980 - - expect(resolveWorkspaceKanbanVirtualLaneDropIndex(scrollElement, 370)).toBe(97) - expect(resolveWorkspaceKanbanVirtualLaneDropIndex(scrollElement, 590)).toBe(102) - expect(resolveWorkspaceKanbanVirtualLaneDropIndicatorY(scrollElement, 102)).toBe(613) - unregister() - }) - - it('selects intermediate never-mounted cards across a jumped lane range', () => { - const { scrollElement, spacerElement } = createLayoutElements() - const unregister = registerLayout(scrollElement, spacerElement) - scrollElement.scrollTop = 3_980 - const board = { - querySelectorAll: (selector: string) => - selector === '[data-workspace-board-lane-scroll]' ? [scrollElement] : [] - } as unknown as HTMLElement - - const cardRects = getAreaSelectionCardRects(board) - const selectedIds = getAreaSelectionCardIds( - cardRects, - { left: 0, top: 110, width: 300, height: 480 }, - { - scrollStartContentYByElement: new Map([[scrollElement, 18]]), - currentY: 590 - } - ) - - expect(cardRects.every((card) => card.element === null)).toBe(true) - expect(selectedIds).toHaveLength(ITEM_COUNT) - expect(selectedIds).toContain('w50') - unregister() - }) - - it('does not let stale cleanup remove a newer lane registration', () => { - const { scrollElement, spacerElement } = createLayoutElements() - const unregisterFirst = registerWorkspaceKanbanVirtualLaneLayout({ - scrollElement, - spacerElement, - getItemIds: () => ['old'], - getMeasurements: () => [{ index: 0, start: 0, end: ITEM_HEIGHT }] - }) - const unregisterSecond = registerWorkspaceKanbanVirtualLaneLayout({ - scrollElement, - spacerElement, - getItemIds: () => ['new'], - getMeasurements: () => [{ index: 0, start: 0, end: ITEM_HEIGHT }] - }) - - unregisterFirst() - expect(getWorkspaceKanbanVirtualLaneItemRects(scrollElement)?.map((item) => item.id)).toEqual([ - 'new' - ]) - unregisterSecond() - expect(getWorkspaceKanbanVirtualLaneItemRects(scrollElement)).toBeNull() - }) -}) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.stable-message.test.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.stable-message.test.tsx index c9510cfef4f..d323e01c3f7 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.stable-message.test.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-card-compact-agent-row.stable-message.test.tsx @@ -92,21 +92,4 @@ describe('CompactAgentRow stable assistant message', () => { rerenderRow(makeAgent({ stateStartedAt: 3000 })) expect(container.textContent).not.toContain('First reply') }) - - it('never holds across pings for entries without a turn identity (stateStartedAt 0)', () => { - const container = renderRow(makeAgent({ stateStartedAt: 0, lastAssistantMessage: 'Turn one' })) - expect(container.textContent).toContain('Turn one') - - rerenderRow(makeAgent({ stateStartedAt: 0 })) - expect(container.textContent).not.toContain('Turn one') - }) - - it('drops the held line when the agent leaves working', () => { - const container = renderRow( - makeAgent({ stateStartedAt: 1000, lastAssistantMessage: 'First reply' }) - ) - rerenderRow(makeAgent({ stateStartedAt: 1000, state: 'done' })) - rerenderRow(makeAgent({ stateStartedAt: 1000, state: 'working' })) - expect(container.textContent).not.toContain('First reply') - }) }) diff --git a/src/renderer/src/components/sidebar/workspace-card/identity/child-workspaces-toggle-visibility.test.ts b/src/renderer/src/components/sidebar/workspace-card/identity/child-workspaces-toggle-visibility.test.ts deleted file mode 100644 index f491559e2d2..00000000000 --- a/src/renderer/src/components/sidebar/workspace-card/identity/child-workspaces-toggle-visibility.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, describe, expect, it } from 'vitest' -import { renderHook } from '@testing-library/react' -import { useAppStore } from '@/store' -import type { AppState } from '@/store/types' -import type { WorktreeLineage } from '../../../../../../shared/worktree/lineage-types' -import type { Worktree } from '../../../../../../shared/worktree/types' - -import { - getRenderedLineageChipKeys, - resolveChildWorkspacesToggleGroupKey -} from './child-workspaces-toggle-target' -import { computeRenderedSidebarRows } from '../../worktree-list/listing/rendered-sidebar-worktree-order' -import { useSidebarWorktreeSelection } from '../../worktree-list/navigation/use-selection' -import { getPinnedWorktreeDisplayPolicy } from '../../../../../../shared/sidebar-list/row-types' -import { - setVisibleWorktreeIds, - setVisibleWorktreeShortcutTargets -} from '../../worktree-list/listing/visible-worktrees' -import { computeVisibleWorktrees } from '../../worktree-list/listing/compute-visible-worktrees' -import { buildVisibleWorktreeOptionsFromState } from '../../worktree-list/listing/visible-worktree-options-from-state' -import { repo, worktree } from '../../worktree-list/grouping/worktree-list-groups-test-fixtures' - -const initialState = useAppStore.getInitialState() -const parent: Worktree = { ...worktree, id: 'parent', instanceId: 'parent-instance' } -const child: Worktree = { ...worktree, id: 'child', instanceId: 'child-instance' } -const edge: WorktreeLineage = { - worktreeId: child.id, - worktreeInstanceId: 'child-instance', - parentWorktreeId: parent.id, - parentWorktreeInstanceId: 'parent-instance', - origin: 'manual', - capture: { source: 'manual-action', confidence: 'explicit' }, - createdAt: 1 -} -type HoverDocument = NonNullable[2]> -// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the no-hover fixture supplies only the empty NodeList methods the identity reader uses. -const noHover = { - querySelectorAll: () => ({ length: 0, item: () => null }) -} as unknown as HoverDocument - -function seed(overrides: Partial = {}): AppState { - useAppStore.setState( - { - ...initialState, - repos: [repo], - worktreesByRepo: { [repo.id]: [parent, child] }, - worktreeLineageById: { [child.id]: edge }, - activeWorktreeId: parent.id, - showSleepingWorkspaces: true, - filterRepoIds: [], - groupBy: 'none', - ...overrides - }, - true - ) - return useAppStore.getState() -} - -function target(state: AppState): string | null { - return resolveChildWorkspacesToggleGroupKey(state, getRenderedLineageChipKeys(state), noHover) -} - -describe('child workspace shortcut follows canonical rendered chips', () => { - afterEach(() => { - useAppStore.setState(initialState, true) - setVisibleWorktreeIds(null) - setVisibleWorktreeShortcutTargets(null) - }) - - it('uses the mounted rows when a temporary reveal overrides the sleeping filter', () => { - const state = seed({ showSleepingWorkspaces: false }) - expect(target(state)).toBeNull() - const visibleWorktrees = computeVisibleWorktrees(state.worktreesByRepo, [], { - ...buildVisibleWorktreeOptionsFromState(state, new Map([[repo.id, repo]])), - forcedVisibleWorktreeIds: [child.id] - }) - const sectionRows = computeRenderedSidebarRows(state, visibleWorktrees) - const hook = renderHook(() => - useSidebarWorktreeSelection({ - sectionRows, - pinnedDisplayPolicy: getPinnedWorktreeDisplayPolicy(state.settings) - }) - ) - try { - expect(target(state)).toBe('lineage:parent') - } finally { - hook.unmount() - } - }) - - it('does not flip hidden state while a mounted host drag removes the cards', () => { - const state = seed() - const hook = renderHook(() => - useSidebarWorktreeSelection({ - sectionRows: [], - pinnedDisplayPolicy: getPinnedWorktreeDisplayPolicy(state.settings) - }) - ) - try { - expect(target(state)).toBeNull() - } finally { - hook.unmount() - } - }) -}) diff --git a/src/renderer/src/components/sidebar/workspace-card/review/workspace-hover-attachments.test.ts b/src/renderer/src/components/sidebar/workspace-card/review/workspace-hover-attachments.test.ts deleted file mode 100644 index 85ebb649c9d..00000000000 --- a/src/renderer/src/components/sidebar/workspace-card/review/workspace-hover-attachments.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { Worktree, WorkspaceAttachment } from '../../../../../../shared/worktree/types' -import { getWorkspaceAttachmentKey } from '../../../../../../shared/workspace-attachments/workspace-attachment-normalization' -import { getWorkspaceHoverAttachments } from './workspace-hover-attachments' -const workspace: Worktree = { - id: 'repo::/repo/feature', - repoId: 'repo', - path: '/repo/feature', - displayName: 'Feature', - branch: 'feature', - head: 'abc', - isBare: false, - isMainWorktree: false, - isArchived: false, - isPinned: false, - isUnread: false, - sortOrder: 0, - lastActivityAt: 1, - comment: '', - linkedIssue: null, - linkedLinearIssue: null, - linkedPR: 57 -} -const local: WorkspaceAttachment = { - provider: 'github', - type: 'pr', - number: 57, - url: 'https://github.com/acme/orca/pull/57' -} -const other: WorkspaceAttachment = { ...local, url: 'https://github.com/other/orca/pull/57' } -describe('source-safe linked hover details', () => { - it('uses matching review URL to disambiguate the same number across repositories', () => { - const result = getWorkspaceHoverAttachments( - { ...workspace, linkedItems: [other, local] }, - { - review: { - provider: 'github', - number: 57, - title: 'Local review', - url: local.url, - status: 'success' - } - } - ) - expect(result.activeKey).toBe(getWorkspaceAttachmentKey(local)) - expect(result.items[0]?.title).toBeUndefined() - expect(result.items[1]?.title).toBe('Local review') - }) - it('does not guess active checks or assign cached titles when the source is unresolved', () => { - const result = getWorkspaceHoverAttachments( - { ...workspace, linkedItems: [other, local] }, - { review: { provider: 'github', number: 57, title: 'Unknown review' } } - ) - expect(result.activeKey).toBeNull() - expect(result.items.every((item) => !item.title)).toBe(true) - }) - it('does not choose between identical URLs owned by different source contexts', () => { - const localHost = { - ...local, - taskSourceContext: { - kind: 'task-source' as const, - provider: 'github' as const, - projectId: 'repo', - hostId: 'local' as const - } - } - const otherHost = { - ...local, - taskSourceContext: { - kind: 'task-source' as const, - provider: 'github' as const, - projectId: 'repo', - hostId: 'runtime:other' as const - } - } - const result = getWorkspaceHoverAttachments( - { ...workspace, linkedItems: [localHost, otherHost] }, - { review: { provider: 'github', number: 57, title: 'Review', url: local.url } } - ) - expect(result.activeKey).toBeNull() - }) -}) diff --git a/src/renderer/src/components/sidebar/workspace-card/review/worktree-card-pr-display.test.ts b/src/renderer/src/components/sidebar/workspace-card/review/worktree-card-pr-display.test.ts deleted file mode 100644 index 665f5c9056f..00000000000 --- a/src/renderer/src/components/sidebar/workspace-card/review/worktree-card-pr-display.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { HostedReviewInfo } from '../../../../../../shared/source-control/hosted-review/hosted-review-contracts' -import type { PRInfo } from '../../../../../../shared/github/pull-request-types' -import { - getWorktreeCardPrDisplay, - isCachedMergedBranchPRCurrentForWorktree -} from './worktree-card-pr-display' - -const pr: HostedReviewInfo = { - provider: 'github', - number: 123, - title: 'Ready PR', - state: 'open', - url: 'https://github.com/stablyai/orca/pull/123', - status: 'success', - updatedAt: '2026-05-13T00:00:00.000Z', - mergeable: 'MERGEABLE' -} - -const gitLabReview: HostedReviewInfo = { - provider: 'gitlab', - number: 321, - title: 'Ready MR', - state: 'open', - url: 'https://gitlab.com/stablyai/orca/-/merge_requests/321', - status: 'success', - updatedAt: '2026-05-13T00:00:00.000Z', - mergeable: 'MERGEABLE' -} - -describe('getWorktreeCardPrDisplay', () => { - it('still suppresses unlinked linked-lookup details when branch provenance names a different PR', () => { - expect( - getWorktreeCardPrDisplay(pr, null, null, null, null, null, { - reviewHintKey: 'github:123', - branchLookupGitHubPRNumber: 999 - }) - ).toBeNull() - }) - - it('does not let a GitHub branch PR number corroborate an unlinked GitLab MR', () => { - expect( - getWorktreeCardPrDisplay(gitLabReview, null, null, null, null, null, { - reviewHintKey: 'gitlab:321', - branchLookupGitHubPRNumber: 321 - }) - ).toBeNull() - }) - - it('does not let branch provenance override linked non-GitHub review metadata', () => { - expect( - getWorktreeCardPrDisplay(pr, null, 321, null, null, null, { - reviewHintKey: 'gitlab:321', - branchLookupGitHubPRNumber: 123 - }) - ).toBeNull() - }) - - it('keeps the linked PR number visible when cached details belong to a different PR', () => { - expect(getWorktreeCardPrDisplay(pr, 456)).toEqual({ - provider: 'github', - number: 456, - title: 'Loading PR...' - }) - }) - - it('keeps the linked GitLab MR number visible when cached details belong to a different MR', () => { - expect(getWorktreeCardPrDisplay(gitLabReview, null, 654)).toEqual({ - provider: 'gitlab', - number: 654, - title: 'Loading MR...' - }) - }) -}) - -describe('isCachedMergedBranchPRCurrentForWorktree', () => { - const mergedPR: PRInfo = { - number: 55, - title: 'Merged PR', - state: 'merged', - url: 'https://github.com/stablyai/orca/pull/55', - checksStatus: 'success', - updatedAt: '2026-07-03T00:00:00.000Z', - mergeable: 'MERGEABLE', - headSha: 'final-head' - } - - it('matches when the worktree head is a confirmed commit of the merged PR', () => { - expect( - isCachedMergedBranchPRCurrentForWorktree( - { ...mergedPR, confirmedContainedHeadOid: 'behind-head' }, - { head: 'behind-head' } - ) - ).toBe(true) - }) - - it('rejects a merged PR when the worktree head is neither the final head nor confirmed', () => { - expect( - isCachedMergedBranchPRCurrentForWorktree( - { ...mergedPR, confirmedContainedHeadOid: 'other-head' }, - { head: 'reused-branch-head' } - ) - ).toBe(false) - }) -}) diff --git a/src/renderer/src/components/sidebar/workspace-creation/base-ref-update/local-base-ref-suggestion-toast.test.tsx b/src/renderer/src/components/sidebar/workspace-creation/base-ref-update/local-base-ref-suggestion-toast.test.tsx deleted file mode 100644 index ed6b18c1ac0..00000000000 --- a/src/renderer/src/components/sidebar/workspace-creation/base-ref-update/local-base-ref-suggestion-toast.test.tsx +++ /dev/null @@ -1,111 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { toast } from 'sonner' -import type { AppState } from '@/store/types' -import type { LocalBaseRefUpdateSuggestion } from '../../../../../../shared/worktree/base-ref-drift-types' -import { showLocalBaseRefUpdateSuggestionToast } from './local-base-ref-suggestion-toast' - -vi.mock('sonner', () => ({ - toast: { - info: vi.fn(), - success: vi.fn(), - error: vi.fn(), - dismiss: vi.fn() - } -})) - -const SUGGESTION: LocalBaseRefUpdateSuggestion = { - baseRef: 'origin/main', - localBranch: 'main', - behind: 2 -} - -const mountedRoots: Root[] = [] - -function makeDeps(overrides: Partial<{ enabled: boolean }> = {}) { - let enabled = overrides.enabled ?? false - const updateSettings = vi.fn(async (updates: Record) => { - if (typeof updates.refreshLocalBaseRefOnWorktreeCreate === 'boolean') { - enabled = updates.refreshLocalBaseRefOnWorktreeCreate - } - }) - return { - updateSettings: updateSettings as unknown as AppState['updateSettings'], - getSettings: () => ({ refreshLocalBaseRefOnWorktreeCreate: enabled }) as AppState['settings'], - openSettingsPage: vi.fn() as AppState['openSettingsPage'], - openSettingsTarget: vi.fn() as AppState['openSettingsTarget'] - } -} - -// Render the ReactNode passed to toast.info as the toast description so we can -// click its in-body buttons the same way the real toast surface would. -function renderToastBody(): HTMLElement { - const description = vi.mocked(toast.info).mock.calls.at(-1)?.[1] - ?.description as React.ReactElement - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - mountedRoots.push(root) - act(() => { - root.render(description) - }) - return container -} - -function clickButton(container: HTMLElement, label: string): void { - const button = [...container.querySelectorAll('button')].find( - (el) => el.textContent?.trim() === label - ) - if (!button) { - throw new Error(`button "${label}" not found`) - } - act(() => { - button.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) -} - -afterEach(() => { - mountedRoots.splice(0).forEach((root) => act(() => root.unmount())) - document.body.innerHTML = '' - vi.clearAllMocks() -}) - -describe('showLocalBaseRefUpdateSuggestionToast', () => { - it('reports failure when enabling cannot persist the setting', async () => { - const deps = makeDeps() - // updateSettings resolves but the flag never flips → treated as a failure. - deps.updateSettings = vi.fn().mockResolvedValue(undefined) as AppState['updateSettings'] - showLocalBaseRefUpdateSuggestionToast(SUGGESTION, deps) - const body = renderToastBody() - - clickButton(body, 'Keep main up to date') - await act(async () => { - await Promise.resolve() - }) - - expect(toast.dismiss).not.toHaveBeenCalled() - expect(toast.error).toHaveBeenCalledWith('Could not turn on Keep Local Main Up to Date', { - description: 'Open Settings and try again.' - }) - }) - - it('does not record a permanent dismissal when opening the Git setting', async () => { - const deps = makeDeps() - showLocalBaseRefUpdateSuggestionToast(SUGGESTION, deps) - const body = renderToastBody() - - clickButton(body, 'Settings › Keep Local Main Up to Date') - const options = vi.mocked(toast.info).mock.calls.at(-1)?.[1] as unknown as { - onDismiss: () => void - } - options.onDismiss() - await Promise.resolve() - - expect(deps.updateSettings).not.toHaveBeenCalledWith({ - localBaseRefSuggestionDismissed: true - }) - }) -}) diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/host-header-drag.test.tsx b/src/renderer/src/components/sidebar/worktree-list/drag/host-header-drag.test.tsx index 25af71cdb2a..9d2d4bcfb1d 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/host-header-drag.test.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/drag/host-header-drag.test.tsx @@ -74,17 +74,4 @@ describe('useHostHeaderDrag', () => { expect(controller.current?.state.draggingHostId).toBe('ssh:host-a') }) - - it('still promotes a drag while the pointer stays down', () => { - const { controller, header } = setup() - - act(() => { - header.dispatchEvent(pointer('pointerdown', { button: 0, clientX: 10, clientY: 10 })) - }) - act(() => { - window.dispatchEvent(pointer('pointermove', { clientX: 40, clientY: 60, buttons: 1 })) - }) - - expect(controller.current?.state.draggingHostId).toBe('ssh:host-a') - }) }) diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/project-group-header-drag-commit.test.ts b/src/renderer/src/components/sidebar/worktree-list/drag/project-group-header-drag-commit.test.ts deleted file mode 100644 index 48878c6638f..00000000000 --- a/src/renderer/src/components/sidebar/worktree-list/drag/project-group-header-drag-commit.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -// @vitest-environment happy-dom -import { describe, expect, it, vi } from 'vitest' - -import { commitProjectGroupHeaderDragDrop } from './project-group-header-drag-commit' -import type { ProjectGroupHeaderDragSession } from './project-group-header-drag-contract' -import type { ProjectGroup } from '../../../../../../shared/project-group-types' - -function group(id: string, overrides: Partial = {}): ProjectGroup { - return { - id, - name: id, - parentPath: null, - parentGroupId: null, - createdFrom: 'manual', - tabOrder: 0, - isCollapsed: false, - color: null, - createdAt: 1, - updatedAt: 1, - ...overrides - } -} - -function makeSession( - groupId: string, - sidebarProjectGroupHeaderIds: readonly string[] -): ProjectGroupHeaderDragSession { - return { - groupId, - bucketKey: 'root', - sidebarProjectGroupHeaderIds, - pointerId: 1, - headerRects: [], - handleEl: document.createElement('div'), - startX: 0, - startY: 0, - latestPointerY: 0, - promoted: true - } -} - -describe('commitProjectGroupHeaderDragDrop', () => { - it('commits dense tabOrder updates for the affected Project Group siblings', () => { - const onCommitProjectGroupTabOrder = vi.fn() - const groups = [ - group('a', { tabOrder: 0 }), - group('b', { tabOrder: 10 }), - group('c', { tabOrder: 20 }) - ] - const projectGroupById = new Map(groups.map((entry) => [entry.id, entry])) - - commitProjectGroupHeaderDragDrop({ - session: makeSession('c', ['a', 'b', 'c']), - sidebarDropIndex: 0, - projectGroupById, - onCommitProjectGroupTabOrder - }) - - expect(onCommitProjectGroupTabOrder.mock.calls).toEqual([ - ['c', 0], - ['a', 1], - ['b', 2] - ]) - }) - - it('computes order only from the captured sibling bucket', () => { - const onCommitProjectGroupTabOrder = vi.fn() - const root = group('root') - const siblingA = group('sibling-a', { parentGroupId: root.id, tabOrder: 0 }) - const siblingB = group('sibling-b', { parentGroupId: root.id, tabOrder: 10 }) - const otherParentGroup = group('other-parent-group', { tabOrder: -100 }) - const projectGroupById = new Map( - [root, siblingA, siblingB, otherParentGroup].map((entry) => [entry.id, entry]) - ) - - commitProjectGroupHeaderDragDrop({ - session: makeSession('sibling-b', ['sibling-a', 'sibling-b']), - sidebarDropIndex: 0, - projectGroupById, - onCommitProjectGroupTabOrder - }) - - expect(onCommitProjectGroupTabOrder.mock.calls).toEqual([ - ['sibling-b', 0], - ['sibling-a', 1] - ]) - }) - - it('does not commit when the drop keeps the group in the same slot', () => { - const onCommitProjectGroupTabOrder = vi.fn() - const groups = [group('a'), group('b'), group('c')] - const projectGroupById = new Map(groups.map((entry) => [entry.id, entry])) - - commitProjectGroupHeaderDragDrop({ - session: makeSession('b', ['a', 'b', 'c']), - sidebarDropIndex: 2, - projectGroupById, - onCommitProjectGroupTabOrder - }) - - expect(onCommitProjectGroupTabOrder).not.toHaveBeenCalled() - }) - - it('does not commit when a stale session no longer contains the dragged group', () => { - const onCommitProjectGroupTabOrder = vi.fn() - const groups = [group('a'), group('b'), group('c')] - const projectGroupById = new Map(groups.map((entry) => [entry.id, entry])) - - commitProjectGroupHeaderDragDrop({ - session: makeSession('c', ['a', 'b']), - sidebarDropIndex: 0, - projectGroupById, - onCommitProjectGroupTabOrder - }) - - expect(onCommitProjectGroupTabOrder).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/project-header-drag-commit.test.ts b/src/renderer/src/components/sidebar/worktree-list/drag/project-header-drag-commit.test.ts deleted file mode 100644 index 67727e4776c..00000000000 --- a/src/renderer/src/components/sidebar/worktree-list/drag/project-header-drag-commit.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -// @vitest-environment happy-dom -import { describe, expect, it, vi } from 'vitest' - -import { commitProjectHeaderDragDrop } from './project-header-drag-commit' -import type { ProjectHeaderDragSession } from './project-header-drag-contract' -import { getProjectHeaderDragBucketKey } from './project-header-drop' -import type { Repo } from '../../../../../../shared/repo-types' - -function makeRepo(id: string, overrides: Partial = {}): Repo { - return { - id, - path: `/${id}`, - displayName: id, - badgeColor: '#000', - addedAt: 0, - ...overrides - } as Repo -} - -function makeSession( - repo: Repo, - sidebarRepoHeaderIds: readonly string[] -): ProjectHeaderDragSession { - return { - repo, - bucketKey: getProjectHeaderDragBucketKey(repo), - sidebarRepoHeaderIds, - pointerId: 1, - headerRects: [], - handleEl: document.createElement('div'), - startX: 0, - startY: 0, - latestPointerY: 0, - promoted: true - } -} - -describe('commitProjectHeaderDragDrop', () => { - it('moves a merged paired-host header upward as one stable block', () => { - const onCommitRepoOrder = vi.fn() - const repos = [makeRepo('b'), makeRepo('same'), makeRepo('c')] - const repoById = new Map(repos.map((repo) => [repo.id, repo])) - - commitProjectHeaderDragDrop({ - session: makeSession(makeRepo('same'), ['b', 'same', 'c']), - sidebarDropIndex: 0, - orderedRepoIds: ['b', 'same', 'c', 'same'], - repoById, - liveRepos: repos, - usesProjectGroupOrdering: false, - onCommitRepoOrder, - onCommitProjectGroupOrder: vi.fn() - }) - - expect(onCommitRepoOrder).toHaveBeenCalledWith(['same', 'same', 'b', 'c']) - }) - - it('commits projectGroupOrder for the dragged row, not the id-keyed twin on another host', () => { - const onCommitProjectGroupOrder = vi.fn() - const repos = [ - makeRepo('a', { projectGroupId: 'group-1' }), - makeRepo('b', { projectGroupId: 'group-1' }), - makeRepo('c', { projectGroupId: 'group-1', executionHostId: 'local' }) - ] - const repoById = new Map(repos.map((repo) => [repo.id, repo])) - const sshTwin = makeRepo('c', { projectGroupId: 'group-1', connectionId: 'ssh-1' }) - - commitProjectHeaderDragDrop({ - session: makeSession(sshTwin, ['a', 'b', 'c']), - sidebarDropIndex: 0, - orderedRepoIds: ['a', 'b', 'c'], - repoById, - liveRepos: [...repos, sshTwin], - usesProjectGroupOrdering: true, - onCommitRepoOrder: vi.fn(), - onCommitProjectGroupOrder - }) - - expect(onCommitProjectGroupOrder).toHaveBeenCalledWith(sshTwin, 'group-1', -1) - }) - - it('drops nothing when the dragged row changed group during the drag', () => { - const onCommitProjectGroupOrder = vi.fn() - const repos = [ - makeRepo('a', { projectGroupId: 'group-1' }), - makeRepo('b', { projectGroupId: 'group-1' }) - ] - const dragged = makeRepo('c', { projectGroupId: 'group-1' }) - - commitProjectHeaderDragDrop({ - session: makeSession(dragged, ['a', 'b', 'c']), - sidebarDropIndex: 0, - orderedRepoIds: ['a', 'b', 'c'], - repoById: new Map([...repos, dragged].map((repo) => [repo.id, repo])), - liveRepos: [...repos, { ...dragged, projectGroupId: 'group-2' }], - usesProjectGroupOrdering: true, - onCommitRepoOrder: vi.fn(), - onCommitProjectGroupOrder - }) - - expect(onCommitProjectGroupOrder).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/NewExternalWorktreesInboxLine.test.tsx b/src/renderer/src/components/sidebar/worktree-list/listing/NewExternalWorktreesInboxLine.test.tsx deleted file mode 100644 index 7e8b3ca55ab..00000000000 --- a/src/renderer/src/components/sidebar/worktree-list/listing/NewExternalWorktreesInboxLine.test.tsx +++ /dev/null @@ -1,87 +0,0 @@ -// @vitest-environment happy-dom - -import { act, type ReactNode } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import NewExternalWorktreesInboxLine from './NewExternalWorktreesInboxLine' - -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: ReactNode }) => <>{children}, - TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children}, - TooltipContent: ({ children }: { children: ReactNode }) => ( - {children} - ) -})) - -const roots: Root[] = [] - -type RenderOverrides = { - hostContextLabel?: string - inboxCount?: number - pending?: boolean - error?: string | null - onReview?: () => void - onSuppress?: () => void -} - -async function renderLine(overrides: RenderOverrides = {}): Promise { - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - roots.push(root) - - await act(async () => { - root.render( - - ) - }) - - return container -} - -function getReviewButton(container: HTMLDivElement): HTMLButtonElement | null { - return container.querySelector('button[aria-label^="Review "]') -} - -describe('NewExternalWorktreesInboxLine', () => { - beforeEach(() => { - globalThis.IS_REACT_ACT_ENVIRONMENT = true - }) - - afterEach(() => { - roots.splice(0).forEach((root) => { - act(() => root.unmount()) - }) - document.body.replaceChildren() - vi.clearAllMocks() - }) - - it('keeps suppress as a hover-revealed control that does not trigger review', async () => { - const onReview = vi.fn() - const onSuppress = vi.fn() - const container = await renderLine({ onReview, onSuppress }) - - const suppressButton = container.querySelector( - 'button[aria-label="Hide external worktrees permanently for orca"]' - ) - expect(suppressButton).not.toBeNull() - expect(suppressButton?.className).toContain('can-hover:group-hover:opacity-100') - expect(container.textContent).toContain("Don't show again") - expect(getReviewButton(container)?.contains(suppressButton)).toBe(false) - - await act(async () => { - suppressButton?.click() - }) - expect(onSuppress).toHaveBeenCalledTimes(1) - expect(onReview).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-child-card.test.ts b/src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-child-card.test.ts deleted file mode 100644 index eae3a5a773c..00000000000 --- a/src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-child-card.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { beforeAll, describe, expect, it, vi } from 'vitest' - -import { - createAppStoreModuleMock, - createDropdownMenuModuleMock, - createProjectHeaderDragModuleMock, - createReactVirtualModuleMock, - createTooltipModuleMock, - createVirtualizedScrollAnchorModuleMock, - createWorktreeCardAgentsModuleMock, - createWorktreeCardModuleMock, - createWorktreeContextMenuModuleMock, - createWorktreeTitleInlineRenameModuleMock, - loadWorktreeList, - mockStore, - renderWorktreeListMarkup -} from './worktree-list-lineage-card-test-harness' -import { getCardOpeningTag } from '../viewport/worktree-list-card-markup-queries' - -import { setLineageFixtureState } from './worktree-list-lineage-store-state' -import { setPinnedFixtureState } from './worktree-list-pinned-store-state' - -vi.mock('@/store', () => createAppStoreModuleMock()) -vi.mock('@tanstack/react-virtual', () => createReactVirtualModuleMock()) -vi.mock('@/hooks/useVirtualizedScrollAnchor', () => createVirtualizedScrollAnchorModuleMock()) -vi.mock('../drag/project-header-drag', () => createProjectHeaderDragModuleMock()) -vi.mock('../../workspace-card/surface/WorktreeCard', () => createWorktreeCardModuleMock()) -vi.mock('../../workspace-card/activity/WorktreeCardAgents', () => - createWorktreeCardAgentsModuleMock() -) -vi.mock('../../workspace-card/identity/WorktreeTitleInlineRename', () => - createWorktreeTitleInlineRenameModuleMock() -) -vi.mock('../../workspace-actions/context-menu/WorktreeContextMenu', () => - createWorktreeContextMenuModuleMock() -) -vi.mock('@/components/ui/tooltip', () => createTooltipModuleMock()) -vi.mock('@/components/ui/dropdown-menu', () => createDropdownMenuModuleMock()) - -describe('WorktreeList lineage child card renderer', () => { - beforeAll(async () => { - await loadWorktreeList() - }, 60_000) - - it('renders recursive lineage descendants through WorktreeCard once', async () => { - setLineageFixtureState() - const markup = await renderWorktreeListMarkup() - - expect(markup.match(/data-worktree-card-id="parent"/g)).toHaveLength(1) - expect(markup.match(/data-worktree-card-id="child"/g)).toHaveLength(1) - expect(markup.match(/data-worktree-card-id="grandchild"/g)).toHaveLength(1) - - const parentIndex = markup.indexOf('data-worktree-card-id="parent"') - const childIndex = markup.indexOf('data-worktree-card-id="child"') - const grandchildIndex = markup.indexOf('data-worktree-card-id="grandchild"') - - expect(parentIndex).toBeGreaterThan(-1) - expect(childIndex).toBeGreaterThan(parentIndex) - expect(grandchildIndex).toBeGreaterThan(childIndex) - expect(getCardOpeningTag(markup, 'child')).toContain('data-lineage-child-count="1"') - }) - - it('points aria-activedescendant at the active lineage child row', async () => { - setLineageFixtureState() - mockStore.state.activeWorktreeId = 'child' - const markup = await renderWorktreeListMarkup() - - expect(markup).toContain('aria-activedescendant="worktree-list-option-all%3A%7Cchild"') - }) - - it('points aria-activedescendant at the pinned row for active pinned workspaces', async () => { - setPinnedFixtureState() - const markup = await renderWorktreeListMarkup() - - expect(markup).toContain('aria-activedescendant="worktree-list-option-pinned%3A%7Cpinned"') - expect(markup).toContain('id="worktree-list-option-pinned%3A%7Cpinned"') - expect(markup).not.toContain('id="worktree-list-option-all%3A%7Cpinned"') - }) - - it('points aria-activedescendant at the natural duplicate when enabled', async () => { - setPinnedFixtureState() - mockStore.state.settings = { showPinnedWorktreesInGroups: true } - const markup = await renderWorktreeListMarkup() - - expect(markup).toContain('aria-activedescendant="worktree-list-option-all%3A%7Cpinned"') - expect(markup).toContain('id="worktree-list-option-pinned%3A%7Cpinned"') - expect(markup).toContain('id="worktree-list-option-all%3A%7Cpinned"') - }) -}) diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/imported-worktrees-card-actions.test.ts b/src/renderer/src/components/sidebar/worktree-list/listing/imported-worktrees-card-actions.test.ts deleted file mode 100644 index d9b0715fef5..00000000000 --- a/src/renderer/src/components/sidebar/worktree-list/listing/imported-worktrees-card-actions.test.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -import { - getImportedWorktreesKeepHiddenError, - getImportedWorktreesShowError, - keepImportedWorktreesHiddenCard, - showImportedWorktreesCard, - type ImportedWorktreeCardActionState -} from './imported-worktrees-card-actions' - -const projectId = 'repo-1' - -describe('imported worktrees card actions', () => { - const updateRepo = vi.fn() - const fetchWorktrees = vi.fn() - const setCardState = - vi.fn<(projectId: string, state: ImportedWorktreeCardActionState | null) => void>() - - beforeEach(() => { - vi.clearAllMocks() - updateRepo.mockResolvedValue(true) - fetchWorktrees.mockResolvedValue(true) - }) - - it('shows discovered worktrees after visibility update and refresh succeed', async () => { - await showImportedWorktreesCard({ projectId, updateRepo, fetchWorktrees, setCardState }) - - expect(updateRepo).toHaveBeenCalledWith(projectId, { externalWorktreeVisibility: 'show' }) - expect(fetchWorktrees).toHaveBeenCalledWith(projectId, { requireAuthoritative: true }) - expect(setCardState).toHaveBeenNthCalledWith(1, projectId, { - pending: true, - error: null - }) - expect(setCardState).toHaveBeenLastCalledWith(projectId, null) - }) - - it('rolls visibility back when refresh fails after showing', async () => { - fetchWorktrees.mockResolvedValueOnce(false) - - await showImportedWorktreesCard({ projectId, updateRepo, fetchWorktrees, setCardState }) - - expect(updateRepo).toHaveBeenNthCalledWith(1, projectId, { externalWorktreeVisibility: 'show' }) - expect(updateRepo).toHaveBeenNthCalledWith(2, projectId, { externalWorktreeVisibility: 'hide' }) - expect(setCardState).toHaveBeenLastCalledWith(projectId, { - pending: false, - error: getImportedWorktreesShowError() - }) - }) - - it('preserves force-visible state during a retry after rollback failure', async () => { - updateRepo.mockResolvedValueOnce(false) - - await showImportedWorktreesCard({ - projectId, - forceVisible: true, - updateRepo, - fetchWorktrees, - setCardState - }) - - expect(fetchWorktrees).not.toHaveBeenCalled() - expect(setCardState).toHaveBeenNthCalledWith(1, projectId, { - pending: true, - error: null, - forceVisible: true - }) - expect(setCardState).toHaveBeenLastCalledWith(projectId, { - pending: false, - error: getImportedWorktreesShowError(), - forceVisible: true - }) - }) - - it('keeps the card force-visible when rollback fails after a refresh failure', async () => { - fetchWorktrees.mockResolvedValueOnce(false) - updateRepo.mockResolvedValueOnce(true).mockResolvedValueOnce(false) - - await showImportedWorktreesCard({ projectId, updateRepo, fetchWorktrees, setCardState }) - - expect(updateRepo).toHaveBeenNthCalledWith(1, projectId, { externalWorktreeVisibility: 'show' }) - expect(updateRepo).toHaveBeenNthCalledWith(2, projectId, { externalWorktreeVisibility: 'hide' }) - expect(setCardState).toHaveBeenLastCalledWith(projectId, { - pending: false, - error: getImportedWorktreesShowError(), - forceVisible: true - }) - }) - - it('dismisses the card when keep-hidden update succeeds', async () => { - await keepImportedWorktreesHiddenCard({ - projectId, - updateRepo, - setCardState, - hiddenWorktreePaths: ['/scratch/external'], - existingBaselinePaths: ['/scratch/old'] - }) - - expect(updateRepo).toHaveBeenCalledWith(projectId, { - externalWorktreeVisibilityPromptDismissedAt: expect.any(Number), - externalWorktreeInboxBaselinePaths: ['/scratch/old', '/scratch/external'] - }) - expect(setCardState).toHaveBeenLastCalledWith(projectId, null) - }) - - it('leaves the card visible when keep-hidden update fails', async () => { - updateRepo.mockResolvedValueOnce(false) - - await keepImportedWorktreesHiddenCard({ projectId, updateRepo, setCardState }) - - expect(setCardState).toHaveBeenLastCalledWith(projectId, { - pending: false, - error: getImportedWorktreesKeepHiddenError() - }) - }) -}) diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/new-external-worktrees-inbox-actions.test.ts b/src/renderer/src/components/sidebar/worktree-list/listing/new-external-worktrees-inbox-actions.test.ts deleted file mode 100644 index 209735d3ddd..00000000000 --- a/src/renderer/src/components/sidebar/worktree-list/listing/new-external-worktrees-inbox-actions.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -import type { Repo } from '../../../../../../shared/repo-types' -import { - importNewExternalWorktreeInboxPaths, - keepNewExternalWorktreeInboxHidden, - suppressNewExternalWorktreeInbox -} from './new-external-worktrees-inbox-actions' - -const projectId = 'repo-1' -const repo: Pick = { - externalWorktreeInboxBaselinePaths: ['/scratch/old'], - importedExternalWorktreePaths: [] -} - -describe('new external worktree inbox actions', () => { - it('imports inbox worktrees into the sidebar allowlist', async () => { - const updateRepo = vi.fn().mockResolvedValue(true) - const fetchWorktrees = vi.fn().mockResolvedValue(true) - const setInboxState = vi.fn() - - await importNewExternalWorktreeInboxPaths({ - projectId, - repo, - worktreePaths: ['/scratch/new'], - updateRepo, - fetchWorktrees, - setInboxState - }) - - expect(updateRepo).toHaveBeenCalledWith(projectId, { - importedExternalWorktreePaths: ['/scratch/new'], - externalWorktreeInboxBaselinePaths: ['/scratch/old', '/scratch/new'] - }) - expect(fetchWorktrees).toHaveBeenCalledWith(projectId, { requireAuthoritative: true }) - expect(setInboxState).toHaveBeenLastCalledWith(projectId, null) - }) - - it('rolls import path lists back with explicit empty arrays when refresh fails', async () => { - const updateRepo = vi.fn().mockResolvedValue(true) - const fetchWorktrees = vi.fn().mockResolvedValue(false) - const setInboxState = vi.fn() - - await importNewExternalWorktreeInboxPaths({ - projectId, - repo: {}, - worktreePaths: ['/scratch/new'], - updateRepo, - fetchWorktrees, - setInboxState - }) - - expect(updateRepo).toHaveBeenNthCalledWith(1, projectId, { - importedExternalWorktreePaths: ['/scratch/new'], - externalWorktreeInboxBaselinePaths: ['/scratch/new'] - }) - expect(updateRepo).toHaveBeenNthCalledWith(2, projectId, { - importedExternalWorktreePaths: [], - externalWorktreeInboxBaselinePaths: [] - }) - }) - - it('extends the inbox baseline when keeping a batch hidden', async () => { - const updateRepo = vi.fn().mockResolvedValue(true) - const setInboxState = vi.fn() - - await keepNewExternalWorktreeInboxHidden({ - projectId, - repo, - worktreePaths: ['/scratch/new'], - updateRepo, - fetchWorktrees: vi.fn(), - setInboxState - }) - - expect(setInboxState).toHaveBeenNthCalledWith(1, projectId, { pending: true, error: null }) - expect(updateRepo).toHaveBeenCalledWith(projectId, { - externalWorktreeInboxBaselinePaths: ['/scratch/old', '/scratch/new'] - }) - expect(setInboxState).toHaveBeenLastCalledWith(projectId, null) - }) - - it('permanently suppresses the inbox and baselines the current batch', async () => { - const updateRepo = vi.fn().mockResolvedValue(true) - const setInboxState = vi.fn() - - const suppressed = await suppressNewExternalWorktreeInbox({ - projectId, - repo, - worktreePaths: ['/scratch/new'], - updateRepo, - setInboxState - }) - - expect(suppressed).toBe(true) - expect(updateRepo).toHaveBeenCalledWith(projectId, { - externalWorktreeDiscoverySuppressedAt: expect.any(Number), - externalWorktreeInboxBaselinePaths: ['/scratch/old', '/scratch/new'] - }) - expect(setInboxState).toHaveBeenLastCalledWith(projectId, null) - }) -}) diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/worktree-list-lineage-store-state.ts b/src/renderer/src/components/sidebar/worktree-list/listing/worktree-list-lineage-store-state.ts deleted file mode 100644 index 164438c64e3..00000000000 --- a/src/renderer/src/components/sidebar/worktree-list/listing/worktree-list-lineage-store-state.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { vi } from 'vitest' -import type { ProjectGroup } from '../../../../../../shared/project-group-types' -import type { WorktreeLineage } from '../../../../../../shared/worktree/lineage-types' -import type { Worktree } from '../../../../../../shared/worktree/types' -import { cloneDefaultWorkspaceStatuses } from '../../../../../../shared/workspace-statuses' -import { mockStore } from './worktree-list-lineage-card-test-harness' -import { - makeFolderWorkspacePathStatusMockState, - makeFolderWorkspacePathStatusState, - makeRepo, - makeWorktree -} from './worktree-list-lineage-card-test-fixtures' - -function makeLineage(worktree: Worktree, parent: Worktree): WorktreeLineage { - return { - worktreeId: worktree.id, - worktreeInstanceId: worktree.instanceId!, - parentWorktreeId: parent.id, - parentWorktreeInstanceId: parent.instanceId!, - origin: 'orchestration', - capture: { source: 'orchestration-context', confidence: 'explicit' }, - createdAt: 1 - } -} - -export function setLineageFixtureState( - groupBy: 'none' | 'repo' | 'workspace-status' = 'none', - options: { - childWorktreeOverrides?: Partial - deletingWorktreeIds?: string[] - folderBackedProjectGroup?: boolean - projectGroupDepth?: number - projectGrouped?: boolean - unreadWorktreeIds?: string[] - } = {} -): void { - const projectGroupDepth = Math.max(0, Math.floor(options.projectGroupDepth ?? 0)) - const parentProjectGroups: ProjectGroup[] = Array.from( - { length: projectGroupDepth }, - (_, index) => ({ - id: `project-group-parent-${index + 1}`, - name: `Parent ${index + 1}`, - parentPath: `/tmp/lineage-order/parent-${index + 1}`, - parentGroupId: index === 0 ? null : `project-group-parent-${index}`, - createdFrom: options.folderBackedProjectGroup ? 'folder-scan' : 'manual', - tabOrder: index, - isCollapsed: false, - color: null, - createdAt: 1, - updatedAt: 1 - }) - ) - const projectGroup: ProjectGroup = { - id: 'project-group-1', - name: 'Personal', - parentPath: '/tmp/lineage-order', - parentGroupId: projectGroupDepth > 0 ? `project-group-parent-${projectGroupDepth}` : null, - createdFrom: options.folderBackedProjectGroup ? 'folder-scan' : 'manual', - tabOrder: projectGroupDepth, - isCollapsed: false, - color: null, - createdAt: 1, - updatedAt: 1 - } - const repo = { - ...makeRepo(), - projectGroupId: options.projectGrouped ? projectGroup.id : null - } - const parent = makeWorktree({ - id: 'parent', - instanceId: 'parent-instance', - displayName: 'lineage parent', - branch: 'parent-branch', - sortOrder: 30 - }) - const child = makeWorktree({ - id: 'child', - instanceId: 'child-instance', - displayName: 'lineage child with agent', - branch: 'child-branch', - sortOrder: 20 - }) - Object.assign(child, options.childWorktreeOverrides) - const grandchild = makeWorktree({ - id: 'grandchild', - instanceId: 'grandchild-instance', - displayName: 'lineage grandchild', - branch: 'grandchild-branch', - sortOrder: 10 - }) - const unreadWorktreeIds = new Set(options.unreadWorktreeIds ?? []) - parent.isUnread = unreadWorktreeIds.has(parent.id) - child.isUnread = unreadWorktreeIds.has(child.id) - grandchild.isUnread = unreadWorktreeIds.has(grandchild.id) - - mockStore.state = { - ...makeFolderWorkspacePathStatusMockState(), - activeModal: '', - activeView: 'terminal', - activeWorktreeId: null, - agentStatusEpoch: 0, - agentStatusByPaneKey: {}, - browserTabsByWorktree: {}, - clearPendingRevealWorktreeId: vi.fn(), - collapsedGroups: new Set(), - deleteStateByWorktreeId: Object.fromEntries( - (options.deletingWorktreeIds ?? []).map((worktreeId) => [ - worktreeId, - { isDeleting: true, error: null, canForceDelete: false } - ]) - ), - filterRepoIds: [], - ...makeFolderWorkspacePathStatusState(), - groupBy, - hideDefaultBranchWorkspace: false, - issueCache: {}, - migrationUnsupportedByPtyId: {}, - openModal: vi.fn(), - pendingRevealWorktree: null, - prCache: {}, - prVisibleRefreshGeneration: 0, - projectGroups: options.projectGrouped ? [...parentProjectGroups, projectGroup] : [], - ptyIdsByTabId: {}, - reorderRepos: vi.fn(), - reportVisibleGitHubPRRefreshCandidates: vi.fn(), - retainedAgentsByPaneKey: {}, - repos: [repo], - runtimePaneTitlesByTabId: {}, - setFilterRepoIds: vi.fn(), - setHideDefaultBranchWorkspace: vi.fn(), - setRenamingWorktreeId: vi.fn(), - setShowSleepingWorkspaces: vi.fn(), - setSortBy: vi.fn(), - settings: null, - renamingWorktreeId: null, - showSleepingWorkspaces: true, - sortBy: 'manual', - sortEpoch: 0, - sshConnectedGeneration: 0, - sshConnectionStates: new Map(), - sshTargetLabels: new Map(), - tabsByWorktree: {}, - terminalLayoutsByTabId: {}, - toggleCollapsedGroup: vi.fn(), - updateWorktreeMeta: vi.fn(), - updateWorktreesMeta: vi.fn(), - // Use the all-host default so host filtering cannot remove fixture rows. - workspaceHostScope: 'all', - workspaceStatuses: groupBy === 'workspace-status' ? cloneDefaultWorkspaceStatuses() : [], - worktreeCardProperties: ['status', 'inline-agents'], - worktreeLineageById: { - [child.id]: makeLineage(child, parent), - [grandchild.id]: makeLineage(grandchild, child) - }, - worktreesByRepo: { - [repo.id]: [parent, child, grandchild] - } - } -} diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/worktree-list-pinned-store-state.ts b/src/renderer/src/components/sidebar/worktree-list/listing/worktree-list-pinned-store-state.ts deleted file mode 100644 index 25e4d7ca873..00000000000 --- a/src/renderer/src/components/sidebar/worktree-list/listing/worktree-list-pinned-store-state.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { vi } from 'vitest' -import { mockStore } from './worktree-list-lineage-card-test-harness' -import { - makeFolderWorkspacePathStatusMockState, - makeFolderWorkspacePathStatusState, - makeRepo, - makeWorktree -} from './worktree-list-lineage-card-test-fixtures' - -export function setPinnedFixtureState(): void { - const repo = makeRepo() - const pinned = makeWorktree({ - id: 'pinned', - instanceId: 'pinned-instance', - displayName: 'pinned workspace', - branch: 'pinned-branch', - sortOrder: 20 - }) - pinned.isPinned = true - const normal = makeWorktree({ - id: 'normal', - instanceId: 'normal-instance', - displayName: 'normal sibling', - branch: 'normal-branch', - sortOrder: 10 - }) - - mockStore.state = { - ...makeFolderWorkspacePathStatusMockState(), - activeModal: '', - activeView: 'terminal', - activeWorktreeId: pinned.id, - agentStatusEpoch: 0, - agentStatusByPaneKey: {}, - browserTabsByWorktree: {}, - clearPendingRevealWorktreeId: vi.fn(), - collapsedGroups: new Set(), - deleteStateByWorktreeId: {}, - filterRepoIds: [], - ...makeFolderWorkspacePathStatusState(), - groupBy: 'none', - hideDefaultBranchWorkspace: false, - issueCache: {}, - migrationUnsupportedByPtyId: {}, - openModal: vi.fn(), - pendingRevealWorktree: null, - prCache: {}, - prVisibleRefreshGeneration: 0, - projectGroups: [], - ptyIdsByTabId: {}, - reorderRepos: vi.fn(), - reportVisibleGitHubPRRefreshCandidates: vi.fn(), - retainedAgentsByPaneKey: {}, - repos: [repo], - runtimePaneTitlesByTabId: {}, - setFilterRepoIds: vi.fn(), - setHideDefaultBranchWorkspace: vi.fn(), - setRenamingWorktreeId: vi.fn(), - setShowSleepingWorkspaces: vi.fn(), - setSortBy: vi.fn(), - settings: null, - renamingWorktreeId: null, - showSleepingWorkspaces: true, - sortBy: 'manual', - sortEpoch: 0, - sshConnectedGeneration: 0, - sshConnectionStates: new Map(), - sshTargetLabels: new Map(), - tabsByWorktree: {}, - terminalLayoutsByTabId: {}, - toggleCollapsedGroup: vi.fn(), - updateWorktreeMeta: vi.fn(), - updateWorktreesMeta: vi.fn(), - workspaceHostScope: 'all', - workspaceStatuses: [], - worktreeCardProperties: ['status', 'inline-agents'], - worktreeLineageById: {}, - worktreesByRepo: { - [repo.id]: [pinned, normal] - } - } -} diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/worktree-header-section-boundaries.test.ts b/src/renderer/src/components/sidebar/worktree-list/viewport/worktree-header-section-boundaries.test.ts deleted file mode 100644 index a78db2a8e81..00000000000 --- a/src/renderer/src/components/sidebar/worktree-list/viewport/worktree-header-section-boundaries.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { - getProjectGroupHeaderSectionEndByGroupId, - getRepoHeaderSectionEndByRepoId -} from './worktree-header-section-boundaries' -import type { RenderRow } from '../listing/render-row' - -const repoHeader = (id: string): RenderRow => - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the boundary reader only reads type, key, repo.id and projectGroup.id. - ({ type: 'header', key: `repo:${id}`, label: id, count: 1, repo: { id } }) as RenderRow -const groupHeader = (id: string): RenderRow => - ({ - type: 'header', - key: `group:${id}`, - label: id, - count: 1, - projectGroup: { id }, - projectGroupDepth: 0 - }) as RenderRow -const item = { type: 'item' } as RenderRow - -// Estimated starts: first header 28, later headers 32, items 116. -const rows = [repoHeader('a'), item, repoHeader('b'), item, repoHeader('c'), item] -const startOfB = 28 + 116 -const startOfC = startOfB + 32 + 116 - -describe('getRepoHeaderSectionEndByRepoId', () => { - it('ends a section at the successor from the header’s own bucket', () => { - const ends = getRepoHeaderSectionEndByRepoId({ - rows, - firstHeaderIndex: 0, - sidebarRepoHeaderIdsByBucket: new Map([ - ['group:one', ['a', 'b']], - ['group:two', ['a', 'c']] - ]), - repoHeaderBucketByRepoId: new Map([ - ['a', 'group:two'], - ['b', 'group:one'], - ['c', 'group:two'] - ]) - }) - - // Regression: a successor index keyed on id alone picked `b` from the first bucket. - expect(ends.get('a')).toBe(startOfC) - expect(ends.get('b')).toBe(startOfC) - }) - - it('resolves a header id that renders twice to its first row, matching findIndex', () => { - const ends = getRepoHeaderSectionEndByRepoId({ - rows: [repoHeader('a'), item, repoHeader('b'), item, repoHeader('b')], - firstHeaderIndex: 0, - sidebarRepoHeaderIdsByBucket: new Map([['ungrouped', ['a', 'b', 'b']]]), - repoHeaderBucketByRepoId: new Map([ - ['a', 'ungrouped'], - ['b', 'ungrouped'] - ]) - }) - - expect(ends.get('a')).toBe(startOfB) - // The first `b` succeeds itself; a last-wins index would jump to the second `b` row. - expect(ends.get('b')).toBe(startOfB) - }) -}) - -describe('getProjectGroupHeaderSectionEndByGroupId', () => { - it('ends a section at the successor from the group’s own bucket', () => { - const ends = getProjectGroupHeaderSectionEndByGroupId({ - rows: [groupHeader('a'), item, groupHeader('b'), item, groupHeader('c'), item], - firstHeaderIndex: 0, - sidebarProjectGroupHeaderIdsByBucket: new Map([ - ['root', ['a', 'b']], - ['parent:x', ['a', 'c']] - ]), - projectGroupHeaderBucketByGroupId: new Map([ - ['a', 'parent:x'], - ['b', 'root'], - ['c', 'parent:x'] - ]) - }) - - expect(ends.get('a')).toBe(startOfC) - }) -}) diff --git a/src/renderer/src/components/status-bar/workspace-space-breakdown-list.test.tsx b/src/renderer/src/components/status-bar/workspace-space-breakdown-list.test.tsx deleted file mode 100644 index b221856a9e4..00000000000 --- a/src/renderer/src/components/status-bar/workspace-space-breakdown-list.test.tsx +++ /dev/null @@ -1,96 +0,0 @@ -// @vitest-environment happy-dom - -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { WorkspaceSpaceBreakdownList } from './workspace-space-breakdown-list' -import type { - WorkspaceSpaceItem, - WorkspaceSpaceWorktree -} from '../../../../shared/workspace-disk-space/workspace-space-types' - -const revealInFileManager = vi.hoisted(() => vi.fn()) -vi.mock('@/lib/reveal-in-file-manager', () => ({ - getRevealInFileManagerLabel: () => 'Reveal in Finder', - revealInFileManager -})) - -function item(name: string, sizeBytes: number): WorkspaceSpaceItem { - return { name, path: `/workspace/${name}`, kind: 'directory', sizeBytes } -} - -function worktree(overrides: Partial): WorkspaceSpaceWorktree { - return { - worktreeId: 'wt', - repoId: 'repo', - repoDisplayName: 'repo', - repoPath: '/repo', - displayName: 'workspace', - path: '/workspace', - branch: 'refs/heads/main', - isMainWorktree: false, - isRemote: false, - isSparse: false, - canDelete: true, - lastActivityAt: 0, - status: 'ok', - error: null, - scannedAt: 0, - sizeBytes: 0, - reclaimableBytes: 0, - skippedEntryCount: 0, - topLevelItems: [], - omittedTopLevelItemCount: 0, - omittedTopLevelSizeBytes: 0, - ...overrides - } -} - -function renderedRowNames(container: HTMLElement): string[] { - return Array.from(container.querySelectorAll('span.font-medium')).map( - (node) => node.textContent ?? '' - ) -} - -afterEach(() => { - cleanup() - revealInFileManager.mockReset() -}) - -describe('WorkspaceSpaceBreakdownList', () => { - it('reveals the selected top-level folder from its context menu', () => { - render( - - ) - - fireEvent.contextMenu(screen.getByText('src')) - fireEvent.click(screen.getByText('Reveal in Finder')) - expect(revealInFileManager).toHaveBeenCalledWith('/workspace/src', 'local') - }) - - it('keeps compacted folder details available in the overflow popover', () => { - const { container } = render( - - ) - - expect(renderedRowNames(container)).toEqual(['first', 'second', 'third', 'fourth']) - fireEvent.click(screen.getByText('Show more folder details')) - expect(screen.getAllByText('fifth')).toHaveLength(1) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/closed-terminal-leaf-notice.test.ts b/src/renderer/src/components/terminal-pane/closed-terminal-leaf-notice.test.ts deleted file mode 100644 index 19c4a55f976..00000000000 --- a/src/renderer/src/components/terminal-pane/closed-terminal-leaf-notice.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { TerminalLayoutSnapshot } from '../../../../shared/workspace-layout/terminal-tab-types' -import { CLOSE_TERMINAL_PANE_EVENT } from '@/constants/terminal' - -const TAB_ID = 'tab-1' -const LEAF_ID = '11111111-1111-4111-8111-111111111111' -const SIBLING_LEAF_ID = '22222222-2222-4222-8222-222222222222' - -const splitLayout: TerminalLayoutSnapshot = { - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: LEAF_ID }, - second: { type: 'leaf', leafId: SIBLING_LEAF_ID } - }, - activeLeafId: LEAF_ID, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF_ID]: 'pty-closed', [SIBLING_LEAF_ID]: 'pty-sibling' } -} - -const layouts: Record = {} -const state = { - tabsByWorktree: {}, - terminalLayoutsByTabId: layouts, - runtimePaneTitlesByTabId: {}, - clearTabLaunchAgent: vi.fn(), - updateTabTitle: vi.fn(), - setTabLayout: vi.fn((tabId: string, layout: TerminalLayoutSnapshot) => { - state.terminalLayoutsByTabId[tabId] = layout - }) -} - -vi.mock('@/store', () => ({ useAppStore: { getState: () => state } })) - -import { applyClosedTerminalLeafNotice } from './closed-terminal-leaf-notice' -import { applyTerminalPaneCloseRequest } from './terminal-pane-lifecycle-close' -import { parkedWatchersByTabId } from './terminal-parked-watcher-registry' - -function leafIds(layout: TerminalLayoutSnapshot | undefined): string[] { - return Object.keys(layout?.ptyIdsByLeafId ?? {}) -} - -beforeEach(() => { - state.terminalLayoutsByTabId = { [TAB_ID]: splitLayout } - state.setTabLayout.mockClear() - vi.stubGlobal('window', new EventTarget()) -}) - -afterEach(() => { - parkedWatchersByTabId.clear() - vi.unstubAllGlobals() -}) - -describe('a split pane main already closed', () => { - it('reaches a mounted pane as a leaf-addressed close', () => { - const details: unknown[] = [] - window.addEventListener(CLOSE_TERMINAL_PANE_EVENT, (event) => - details.push(event instanceof CustomEvent ? event.detail : null) - ) - - applyClosedTerminalLeafNotice(TAB_ID, LEAF_ID) - - expect(details).toEqual([{ tabId: TAB_ID, leafId: LEAF_ID }]) - }) - - it('is ignored by a mounted pane whose exit already removed that leaf', () => { - const manager = { - closePane: vi.fn(), - detachPaneForExternalMove: vi.fn(), - retirePanePreservingPty: vi.fn(), - getNumericIdForLeaf: () => null, - getPanes: () => [{ id: 2 }] - } - const closeTab = vi.fn() - - const result = applyTerminalPaneCloseRequest({ - detail: { tabId: TAB_ID, leafId: LEAF_ID }, - manager, - closeTab, - closeTabPreservingPty: vi.fn() - }) - - // Why: a numeric pane id would have reached the last-pane branch and closed the whole tab. - expect(result).toBe('ignored') - expect(closeTab).not.toHaveBeenCalled() - expect(manager.closePane).not.toHaveBeenCalled() - }) - - it('collapses a parked tab stored layout once for repeated notices', () => { - parkedWatchersByTabId.set(TAB_ID, { - worktreeId: 'repo::/worktree', - tabPtyId: 'pty-closed', - disposersByPtyId: new Map([['pty-closed', vi.fn()]]), - paneIdByPtyId: new Map() - }) - - applyClosedTerminalLeafNotice(TAB_ID, LEAF_ID) - applyClosedTerminalLeafNotice(TAB_ID, LEAF_ID) - - expect(leafIds(state.terminalLayoutsByTabId[TAB_ID])).toEqual([SIBLING_LEAF_ID]) - expect(state.setTabLayout).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/focus-terminal-pane-event.test.ts b/src/renderer/src/components/terminal-pane/focus-terminal-pane-event.test.ts deleted file mode 100644 index be874a9d4db..00000000000 --- a/src/renderer/src/components/terminal-pane/focus-terminal-pane-event.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { TerminalLeafId } from '../../../../shared/workspace-layout/stable-pane-id' -import { handleFocusTerminalPaneDetail } from './focus-terminal-pane-event' - -const LEAF_ID = '11111111-1111-4111-8111-111111111111' as TerminalLeafId -const OTHER_LEAF_ID = '22222222-2222-4222-8222-222222222222' as TerminalLeafId - -class MockClassList { - private classes = new Set() - - add(value: string): void { - this.classes.add(value) - } - - remove(value: string): void { - this.classes.delete(value) - } - - contains(value: string): boolean { - return this.classes.has(value) - } -} - -function createPaneElement(): HTMLElement { - return { classList: new MockClassList() } as unknown as HTMLElement -} - -function createManager(args?: { numericPaneId?: number | null; leafId?: TerminalLeafId }) { - const container = createPaneElement() - const numericPaneId = args?.numericPaneId ?? 7 - const leafId = args?.leafId ?? LEAF_ID - return { - container, - manager: { - getNumericIdForLeaf: vi.fn(() => numericPaneId), - getPanes: vi.fn(() => [ - { - id: 7, - leafId, - container - } - ]), - setActivePane: vi.fn() - } - } -} - -describe('handleFocusTerminalPaneDetail', () => { - it('focuses and flashes only after the target leaf resolves', () => { - const { container, manager } = createManager() - const acknowledgeAgents = vi.fn() - const surfaceStaleAgentRow = vi.fn() - - handleFocusTerminalPaneDetail( - { - tabId: 'tab-1', - leafId: LEAF_ID, - ackPaneKeyOnSuccess: `tab-1:${LEAF_ID}`, - flashFocusedPane: true - }, - { - tabId: 'tab-1', - manager, - acknowledgeAgents, - surfaceStaleAgentRow - } - ) - - expect(manager.setActivePane).toHaveBeenCalledWith(7, { focus: true }) - expect(container.classList.contains('pane-focus-rim-flash')).toBe(true) - expect(acknowledgeAgents).toHaveBeenCalledWith([`tab-1:${LEAF_ID}`]) - expect(surfaceStaleAgentRow).not.toHaveBeenCalled() - }) - - it('requests follow-output scrolling after resolving the target leaf', () => { - const { manager } = createManager() - const scrollToBottomIfOutputSinceLastView = vi.fn() - - handleFocusTerminalPaneDetail( - { - tabId: 'tab-1', - leafId: LEAF_ID, - scrollToBottomIfOutputSinceLastView: true - }, - { - tabId: 'tab-1', - manager, - acknowledgeAgents: vi.fn(), - surfaceStaleAgentRow: vi.fn(), - scrollToBottomIfOutputSinceLastView - } - ) - - expect(manager.setActivePane).toHaveBeenCalledWith(7, { focus: true }) - expect(scrollToBottomIfOutputSinceLastView).toHaveBeenCalledWith(7) - }) - - it('does not focus, flash, or ack when the numeric pane no longer owns the leaf', () => { - const { container, manager } = createManager({ leafId: OTHER_LEAF_ID }) - const acknowledgeAgents = vi.fn() - const surfaceStaleAgentRow = vi.fn() - - handleFocusTerminalPaneDetail( - { - tabId: 'tab-1', - leafId: LEAF_ID, - ackPaneKeyOnSuccess: `tab-1:${LEAF_ID}`, - flashFocusedPane: true - }, - { - tabId: 'tab-1', - manager, - acknowledgeAgents, - surfaceStaleAgentRow - } - ) - - expect(manager.setActivePane).not.toHaveBeenCalled() - expect(container.classList.contains('pane-focus-rim-flash')).toBe(false) - expect(acknowledgeAgents).not.toHaveBeenCalled() - expect(surfaceStaleAgentRow).toHaveBeenCalledWith('tab-1', LEAF_ID) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/leaf-scrollback-resolution.test.ts b/src/renderer/src/components/terminal-pane/leaf-scrollback-resolution.test.ts deleted file mode 100644 index b787c8c3bbc..00000000000 --- a/src/renderer/src/components/terminal-pane/leaf-scrollback-resolution.test.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { TERMINAL_SCROLLBACK_SESSION_HOMES } from '../../../../shared/workspace-session/workspace-session-terminal-buffers' -import { - resolveLeafScrollbackBuffers, - resolveTabScrollbackBuffers, - type TerminalScrollbackSessionHomes -} from './leaf-scrollback-resolution' - -// Enumerating the cap’s homes makes a new persistence home fail here and in the Pick type until the resolver reads it. -describe.each(TERMINAL_SCROLLBACK_SESSION_HOMES)('resolveTabScrollbackBuffers reads %s', (home) => { - const sessionWithBytesOnlyIn: Record< - (typeof TERMINAL_SCROLLBACK_SESSION_HOMES)[number], - TerminalScrollbackSessionHomes - > = { - terminalLayoutsByTabId: { - terminalLayoutsByTabId: { - 'tab-1': { - root: null, - activeLeafId: null, - expandedLeafId: null, - buffersByLeafId: { 'leaf-1': 'from-shared' } - } - }, - localOnlyScrollbackByTabId: {} - }, - localOnlyScrollbackByTabId: { - terminalLayoutsByTabId: {}, - localOnlyScrollbackByTabId: { 'tab-1': { 'leaf-1': 'from-local-only' } } - } - } - - it('returns the bytes that home holds for the tab', () => { - expect(resolveTabScrollbackBuffers(sessionWithBytesOnlyIn[home], 'tab-1')).toEqual({ - 'leaf-1': home === 'terminalLayoutsByTabId' ? 'from-shared' : 'from-local-only' - }) - expect(resolveTabScrollbackBuffers(sessionWithBytesOnlyIn[home], 'tab-other')).toBeUndefined() - }) -}) - -describe('resolveLeafScrollbackBuffers', () => { - it('returns the shared layout buffers when nothing is held locally', () => { - const shared = { buffersByLeafId: { 'leaf-1': 'shared' } } - expect(resolveLeafScrollbackBuffers({ shared, localOnly: undefined })).toBe( - shared.buffersByLeafId - ) - expect(resolveLeafScrollbackBuffers({ shared, localOnly: {} })).toBe(shared.buffersByLeafId) - }) - - it('returns the local-only buffers when the shared layout holds none', () => { - const localOnly = { 'leaf-1': 'local' } - expect(resolveLeafScrollbackBuffers({ shared: undefined, localOnly })).toBe(localOnly) - expect(resolveLeafScrollbackBuffers({ shared: {}, localOnly })).toBe(localOnly) - }) - - it('lets the local-only copy win a leaf both homes hold, and unions the rest', () => { - expect( - resolveLeafScrollbackBuffers({ - shared: { buffersByLeafId: { 'leaf-1': 'shared-stale', 'leaf-2': 'shared-only' } }, - localOnly: { 'leaf-1': 'local-newer', 'leaf-3': 'local-only' } - }) - ).toEqual({ 'leaf-1': 'local-newer', 'leaf-2': 'shared-only', 'leaf-3': 'local-only' }) - }) - - it('returns undefined when neither home holds anything', () => { - expect( - resolveLeafScrollbackBuffers({ shared: undefined, localOnly: undefined }) - ).toBeUndefined() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/parked-terminal-tab-capture-episodes.test.ts b/src/renderer/src/components/terminal-pane/parked-terminal-tab-capture-episodes.test.ts deleted file mode 100644 index e1b5c9bfda9..00000000000 --- a/src/renderer/src/components/terminal-pane/parked-terminal-tab-capture-episodes.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { RepoConnection } from '../../../../shared/workspace-session/workspace-session-terminal-buffers' -import { captureNewlyParkedTerminalTabs } from './parked-terminal-tab-capture-episodes' -import { shutdownBufferCaptures } from './shutdown-buffer-captures' - -const REMOTE_REPO: RepoConnection = { id: 'repo', connectionId: 'conn-1', executionHostId: null } -const LOCAL_REPO: RepoConnection = { id: 'repo', connectionId: null, executionHostId: 'local' } -const WORKTREE_ID = 'repo::/repo/worktree' - -const storeState: { repos: RepoConnection[] } = { repos: [REMOTE_REPO] } - -vi.mock('../../store', () => ({ - useAppStore: { getState: () => storeState } -})) - -afterEach(() => { - shutdownBufferCaptures.clear() - storeState.repos = [REMOTE_REPO] -}) - -describe('captureNewlyParkedTerminalTabs', () => { - it('serializes a newly parked remote tab once per park episode', () => { - const capture = vi.fn() - shutdownBufferCaptures.set('tab-1', capture) - const ledger = new Set() - - captureNewlyParkedTerminalTabs(WORKTREE_ID, new Set(['tab-1']), ledger) - captureNewlyParkedTerminalTabs(WORKTREE_ID, new Set(['tab-1']), ledger) - - expect(capture).toHaveBeenCalledTimes(1) - // Why localOnly: the per-tab park is the every-hide cadence, so its bytes must stay off the upload. - expect(capture).toHaveBeenCalledWith({ includeLocalBuffers: false, localOnly: true }) - expect(ledger).toEqual(new Set(['tab-1'])) - }) - - it('re-captures after a reveal, because the replay releases the stored copy', () => { - const capture = vi.fn() - shutdownBufferCaptures.set('tab-1', capture) - const ledger = new Set() - - captureNewlyParkedTerminalTabs(WORKTREE_ID, new Set(['tab-1']), ledger) - captureNewlyParkedTerminalTabs(WORKTREE_ID, new Set(), ledger) - expect(ledger.size).toBe(0) - captureNewlyParkedTerminalTabs(WORKTREE_ID, new Set(['tab-1']), ledger) - - expect(capture).toHaveBeenCalledTimes(2) - }) - - it('retries a tab whose pane had no registered capture and captures the rest', () => { - const capture = vi.fn() - shutdownBufferCaptures.set('tab-1', capture) - const ledger = new Set() - - captureNewlyParkedTerminalTabs(WORKTREE_ID, new Set(['tab-1', 'tab-remounting']), ledger) - expect(ledger).toEqual(new Set(['tab-1'])) - - const lateCapture = vi.fn() - shutdownBufferCaptures.set('tab-remounting', lateCapture) - captureNewlyParkedTerminalTabs(WORKTREE_ID, new Set(['tab-1', 'tab-remounting']), ledger) - - expect(capture).toHaveBeenCalledTimes(1) - expect(lateCapture).toHaveBeenCalledTimes(1) - }) - - it('leaves a local worktree alone — its daemon history is the authoritative copy', () => { - const capture = vi.fn() - shutdownBufferCaptures.set('tab-1', capture) - storeState.repos = [LOCAL_REPO] - const ledger = new Set() - - captureNewlyParkedTerminalTabs(WORKTREE_ID, new Set(['tab-1']), ledger) - - expect(capture).not.toHaveBeenCalled() - expect(ledger).toEqual(new Set(['tab-1'])) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/foreground-output-scan.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/foreground-output-scan.test.ts index 1321c84e077..64c7f582954 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/foreground-output-scan.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/foreground-output-scan.test.ts @@ -8,33 +8,6 @@ import { afterEach(() => vi.restoreAllMocks()) describe('foreground synchronized output scan', () => { - it.each([start, end])('bounds searched characters for a flood of %j markers', (marker) => { - const data = marker.repeat(8192) - const originalIndexOf = String.prototype.indexOf - let searchedCharacters = 0 - const spy = vi.spyOn(String.prototype, 'indexOf').mockImplementation(function ( - this: string, - search: string, - position = 0 - ): number { - const result = originalIndexOf.call(this, search, position) - if (this === data && (search === start || search === end)) { - searchedCharacters += (result < 0 ? data.length : result + search.length) - position - } - return result - }) - const result = scanSynchronizedForegroundOutput(data, '', false) - spy.mockRestore() - console.info(JSON.stringify({ markers: 8192, chars: data.length, searchedCharacters })) - expect(result).toEqual({ - started: marker === start, - ended: marker === end, - active: marker === start, - markerTail: data.slice(-7) - }) - expect(searchedCharacters).toBeLessThanOrEqual(data.length * 2) - }) - it('preserves the last marker and records both transitions in the current chunk', () => { expect(scanSynchronizedForegroundOutput(`${end}paint${start}`, '', true)).toEqual({ started: true, @@ -66,15 +39,4 @@ describe('foreground synchronized output scan', () => { }) } }) - - it('leaves the latch unchanged for empty output and malformed lookalikes', () => { - for (const data of ['', 'ordinary output', '\x1b[?2026x'.repeat(2048)]) { - expect(scanSynchronizedForegroundOutput(data, '', true)).toEqual({ - started: false, - ended: false, - active: true, - markerTail: data.slice(-7) - }) - } - }) }) diff --git a/src/renderer/src/components/terminal-pane/remote-layout-scrollback-retention.test.ts b/src/renderer/src/components/terminal-pane/remote-layout-scrollback-retention.test.ts deleted file mode 100644 index c457d589d74..00000000000 --- a/src/renderer/src/components/terminal-pane/remote-layout-scrollback-retention.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { TerminalLayoutSnapshot } from '../../../../shared/workspace-layout/terminal-tab-types' -import { retainLocalScrollbackInRemoteLayout } from './remote-layout-scrollback-retention' - -const LEAF_A = 'leaf-a' -const LEAF_B = 'leaf-b' - -function layout(overrides: Partial = {}): TerminalLayoutSnapshot { - return { - root: { type: 'leaf', leafId: LEAF_A }, - activeLeafId: LEAF_A, - expandedLeafId: null, - ...overrides - } -} - -const SPLIT_ROOT: TerminalLayoutSnapshot['root'] = { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: LEAF_A }, - second: { type: 'leaf', leafId: LEAF_B } -} - -describe('retainLocalScrollbackInRemoteLayout', () => { - it('keeps a parked tab scrollback the host copy never had', () => { - const local = layout({ buffersByLeafId: { [LEAF_A]: 'parked-scrollback' } }) - - const merged = retainLocalScrollbackInRemoteLayout(local, layout()) - - expect(merged.buffersByLeafId).toEqual({ [LEAF_A]: 'parked-scrollback' }) - }) - - it('takes the host structure verbatim when the host added a split while we were away', () => { - const local = layout({ buffersByLeafId: { [LEAF_A]: 'parked-scrollback' } }) - const remote = layout({ root: SPLIT_ROOT, ptyIdsByLeafId: { [LEAF_B]: 'remote:env/pty-b' } }) - - const merged = retainLocalScrollbackInRemoteLayout(local, remote) - - expect(merged.root).toBe(SPLIT_ROOT) - expect(merged.ptyIdsByLeafId).toEqual({ [LEAF_B]: 'remote:env/pty-b' }) - // The shared leaf keeps its bytes; nothing is invented for the leaf the host just added. - expect(merged.buffersByLeafId).toEqual({ [LEAF_A]: 'parked-scrollback' }) - }) - - it('drops scrollback for a leaf the host retired', () => { - const local = layout({ - root: SPLIT_ROOT, - buffersByLeafId: { [LEAF_A]: 'kept', [LEAF_B]: 'retired-pane' } - }) - - const merged = retainLocalScrollbackInRemoteLayout(local, layout()) - - expect(merged.buffersByLeafId).toEqual({ [LEAF_A]: 'kept' }) - }) - - it('prefers the local copy when both sides hold bytes for one leaf', () => { - const local = layout({ buffersByLeafId: { [LEAF_A]: 'captured-since-last-upload' } }) - const remote = layout({ buffersByLeafId: { [LEAF_A]: 'older-upload' } }) - - const merged = retainLocalScrollbackInRemoteLayout(local, remote) - - expect(merged.buffersByLeafId).toEqual({ [LEAF_A]: 'captured-since-last-upload' }) - }) - - it('carries scrollback refs, which name client-local snapshot files only this client can read', () => { - const local = layout({ scrollbackRefsByLeafId: { [LEAF_A]: 'v1-abc' } }) - - const merged = retainLocalScrollbackInRemoteLayout(local, layout()) - - expect(merged.scrollbackRefsByLeafId).toEqual({ [LEAF_A]: 'v1-abc' }) - }) - - it('returns the host layout untouched when this client holds no scrollback', () => { - const remote = layout({ buffersByLeafId: { [LEAF_A]: 'from-another-client' } }) - - expect(retainLocalScrollbackInRemoteLayout(layout(), remote)).toBe(remote) - expect(retainLocalScrollbackInRemoteLayout(undefined, remote)).toBe(remote) - }) - - it('leaves a rootless host layout alone rather than guessing which leaves are live', () => { - const local = layout({ buffersByLeafId: { [LEAF_A]: 'parked-scrollback' } }) - const remote = layout({ root: null }) - - expect(retainLocalScrollbackInRemoteLayout(local, remote)).toBe(remote) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-file-link-target.test.ts b/src/renderer/src/components/terminal-pane/terminal-file-link-target.test.ts deleted file mode 100644 index 67dd652bf8d..00000000000 --- a/src/renderer/src/components/terminal-pane/terminal-file-link-target.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { extractTerminalFileLinks } from '../../../../shared/terminal/links/terminal-links' -import type * as FilePathMappingModule from './terminal-file-path-mapping' -import { - mayCheckFileLinkTargetUnprompted, - resolveFileLinkTarget, - type FileLinkHost -} from './terminal-file-link-target' - -const routing = vi.hoisted(() => { - const state: { connectionId?: string } = {} - return state -}) - -vi.mock('./terminal-file-path-mapping', async (importOriginal) => ({ - ...(await importOriginal()), - getTerminalFileContext: (worktreeId: string, worktreePath: string) => ({ - target: { kind: 'local' }, - worktreeId, - worktreePath, - connectionId: routing.connectionId - }) -})) -vi.mock('./terminal-worktree-path-link', () => ({ - resolveKnownWorktreeRootPathLink: () => null -})) - -function mayCheck(pathText: string, workspace: string): boolean { - const link = extractTerminalFileLinks(pathText).find( - (candidate) => candidate.startIndex === 0 && candidate.endIndex === pathText.length - ) - const host: FileLinkHost = { cwd: workspace, worktreeId: 'wt-1', worktreePath: workspace } - const target = link ? resolveFileLinkTarget(link, host) : null - if (!target) { - throw new Error(`no target for ${pathText}`) - } - return mayCheckFileLinkTargetUnprompted(target, host) -} - -describe('mayCheckFileLinkTargetUnprompted', () => { - it('refuses a network share outside the workspace, on this machine or over SSH', () => { - for (const connectionId of [undefined, 'ssh-1']) { - routing.connectionId = connectionId - try { - for (const workspace of [String.raw`C:\Users\me\repo`, '/home/me/repo']) { - expect(mayCheck(String.raw`\\evil.example\share\a.ts`, workspace)).toBe(false) - expect(mayCheck('//evil.example/share/notes.md', workspace)).toBe(false) - } - expect(mayCheck('src/a.ts', '/home/me/repo')).toBe(true) - } finally { - routing.connectionId = undefined - } - } - }) - - it('allows paths inside a workspace on a network share', () => { - expect(mayCheck('src/a.ts', String.raw`C:\Users\me\repo`)).toBe(true) - expect(mayCheck('src/a.ts', String.raw`\\FileServer\share\repo`)).toBe(true) - expect( - mayCheck(String.raw`\\FILESERVER\Share\repo\src\a.ts`, String.raw`\\fileserver\share\repo`) - ).toBe(true) - }) - - it("allows only the workspace's own WSL distro", () => { - const wslWorkspace = String.raw`\\wsl.localhost\Ubuntu\home\me\repo` - expect(mayCheck('/home/me/repo/a.ts', wslWorkspace)).toBe(true) - expect(mayCheck(String.raw`\\wsl.localhost\ubuntu\etc\hosts.txt`, wslWorkspace)).toBe(true) - expect(mayCheck(String.raw`\\wsl.localhost\Debian\etc\hosts.txt`, wslWorkspace)).toBe(false) - expect(mayCheck('//wsl.localhost/../evil/share/a.ts', wslWorkspace)).toBe(false) - expect( - mayCheck(String.raw`\\wsl.localhost\Debian\etc\hosts.txt`, String.raw`C:\Users\me\repo`) - ).toBe(false) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-layout-leaf-ids.test.ts b/src/renderer/src/components/terminal-pane/terminal-layout-leaf-ids.test.ts deleted file mode 100644 index 59116d282c1..00000000000 --- a/src/renderer/src/components/terminal-pane/terminal-layout-leaf-ids.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { - TerminalLayoutSnapshot, - TerminalPaneLayoutNode -} from '../../../../shared/workspace-layout/terminal-tab-types' -import { normalizeTerminalLayoutSnapshot } from './terminal-layout-leaf-ids' - -const LEAF_1 = '11111111-1111-4111-8111-111111111111' -const LEAF_2 = '22222222-2222-4222-8222-222222222222' -const LEAF_3 = '33333333-3333-4333-8333-333333333333' -const MISSING_LEAF = '99999999-9999-4999-8999-999999999999' - -function split(firstLeafId: string, secondLeafId: string): TerminalPaneLayoutNode { - return { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: firstLeafId }, - second: { type: 'leaf', leafId: secondLeafId } - } -} - -function splitLayout(): TerminalLayoutSnapshot { - return { - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: LEAF_1 }, - second: { - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', leafId: LEAF_2 }, - second: { type: 'leaf', leafId: LEAF_3 } - } - }, - activeLeafId: LEAF_2, - expandedLeafId: LEAF_3, - ptyIdsByLeafId: { - [LEAF_1]: 'pty-1', - [LEAF_2]: 'pty-2', - [LEAF_3]: 'pty-3' - } - } -} - -describe('normalizeTerminalLayoutSnapshot active leaf repair', () => { - it('prefers a rootless active leaf over multiple retained PTY bindings', () => { - const result = normalizeTerminalLayoutSnapshot({ - root: null, - activeLeafId: LEAF_3, - expandedLeafId: null, - ptyIdsByLeafId: { - [LEAF_1]: 'pty-1', - [LEAF_2]: 'pty-2' - } - }) - - expect(result.changed).toBe(false) - expect(result.snapshot.activeLeafId).toBe(LEAF_3) - }) - - it('does not pick an arbitrary rootless PTY binding when multiple remain', () => { - const result = normalizeTerminalLayoutSnapshot({ - root: null, - activeLeafId: null, - expandedLeafId: null, - ptyIdsByLeafId: { - [LEAF_1]: 'pty-1', - [LEAF_2]: 'pty-2' - } - }) - - expect(result.changed).toBe(false) - expect(result.snapshot.activeLeafId).toBeNull() - }) - - it('repairs a hydrated active leaf that has lost its PTY while a sibling is bound', () => { - const result = normalizeTerminalLayoutSnapshot({ - root: split(LEAF_1, LEAF_2), - activeLeafId: LEAF_1, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF_2]: 'pty-2' } - }) - - expect(result.changed).toBe(true) - expect(result.snapshot.activeLeafId).toBe(LEAF_2) - expect(result.snapshot.ptyIdsByLeafId).toEqual({ [LEAF_2]: 'pty-2' }) - }) - - it('repairs stale active leaf ids to the first bound leaf in the root layout', () => { - const layout = splitLayout() - layout.activeLeafId = MISSING_LEAF - - const normalized = normalizeTerminalLayoutSnapshot(layout) - - expect(normalized.changed).toBe(true) - expect(normalized.snapshot.activeLeafId).toBe(LEAF_1) - expect(normalized.snapshot.expandedLeafId).toBe(LEAF_3) - expect(normalized.snapshot.ptyIdsByLeafId).toEqual(layout.ptyIdsByLeafId) - }) - - it('clears stale expanded leaf ids without changing a valid active leaf', () => { - const layout = splitLayout() - layout.expandedLeafId = MISSING_LEAF - - const normalized = normalizeTerminalLayoutSnapshot(layout) - - expect(normalized.changed).toBe(true) - expect(normalized.snapshot.activeLeafId).toBe(LEAF_2) - expect(normalized.snapshot.expandedLeafId).toBeNull() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-link-missing-file-open.test.ts b/src/renderer/src/components/terminal-pane/terminal-link-missing-file-open.test.ts index d0d94b139f8..f3553737293 100644 --- a/src/renderer/src/components/terminal-pane/terminal-link-missing-file-open.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-link-missing-file-open.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { openDetectedFilePath } from './terminal-link-handlers' -import type { FileOpenFailure } from './terminal-file-open-failure' + import { createTerminalLinkTestDoubles } from './terminal-link-handlers-test-fixtures' import { flushAsyncWork, @@ -9,7 +9,7 @@ import { } from './terminal-link-handlers-test-harness' const doubles = createTerminalLinkTestDoubles() -const { storeState, deps, openFileMock, statMock } = doubles +const { storeState, deps, statMock } = doubles vi.mock('@/store', () => ({ useAppStore: { @@ -28,37 +28,7 @@ vi.mock('@/lib/connection-context', () => ({ installTerminalLinkTestEnvironment(doubles) -type OnOpenFailure = (failure: FileOpenFailure) => void - describe('openDetectedFilePath on a path it cannot verify', () => { - it('reports a verified miss', async () => { - setPlatform('Macintosh') - const error = new Error("Error invoking remote method 'fs:stat': Error: ENOENT: no such file") - // A missing file fails both the project check and the user-named one. - statMock.mockRejectedValue(error) - const onOpenFailure = vi.fn() - - openDetectedFilePath('/tmp/src/gone.md', null, null, { ...deps, onOpenFailure }) - await flushAsyncWork() - - expect(openFileMock).not.toHaveBeenCalled() - expect(onOpenFailure).toHaveBeenCalledTimes(1) - expect(onOpenFailure).toHaveBeenCalledWith({ verdict: 'missing', error }) - }) - - it('reports a host that could not answer as unverifiable, not missing', async () => { - setPlatform('Macintosh') - const error = new Error('SSH connection closed') - statMock.mockRejectedValue(error) - const onOpenFailure = vi.fn() - - openDetectedFilePath('/tmp/src/present.md', null, null, { ...deps, onOpenFailure }) - await flushAsyncWork() - - expect(onOpenFailure).toHaveBeenCalledTimes(1) - expect(onOpenFailure.mock.calls[0][0]).toEqual({ verdict: 'unverifiable', error }) - }) - it('skips the callback when a later click superseded the failing one', async () => { setPlatform('Macintosh') let rejectFirstStat!: (error: Error) => void diff --git a/src/renderer/src/components/terminal-pane/terminal-modify-other-keys-enter.test.ts b/src/renderer/src/components/terminal-pane/terminal-modify-other-keys-enter.test.ts deleted file mode 100644 index a097f68f3d2..00000000000 --- a/src/renderer/src/components/terminal-pane/terminal-modify-other-keys-enter.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { TerminalKittyKeyboardModeTracker } from '../../../../shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker' -import { - resolveTerminalShortcutAction, - type TerminalShortcutEvent -} from './terminal-shortcut-policy' - -// Captured with config/scripts/capture-agent-pty-transcript.mjs (pi 0.74.0, isolated HOME). -const FIXTURE_DIR = join(__dirname, '..', '..', '..', '..', 'main', 'runtime', '__fixtures__') - -function readFixture(name: string): string { - return readFileSync(join(FIXTURE_DIR, `${name}.txt`), 'utf8') -} - -function enter(overrides: Partial): TerminalShortcutEvent { - return { - key: 'Enter', - code: 'Enter', - metaKey: false, - ctrlKey: false, - altKey: false, - shiftKey: false, - repeat: false, - ...overrides - } -} - -function resolveForPane(event: TerminalShortcutEvent, modes: TerminalKittyKeyboardModeTracker) { - return resolveTerminalShortcutAction( - event, - true, - 'false', - 0, - false, - undefined, - undefined, - () => modes.flags, - undefined, - undefined, - () => false, - 'orca-first', - undefined, - () => modes.modifyOtherKeys - ) -} - -describe('modified Enter for an app that armed modifyOtherKeys (STA-7701)', () => { - it('sends xterm modifyOtherKeys Enter chords once pi has armed the mode', () => { - const modes = new TerminalKittyKeyboardModeTracker() - modes.scan(readFixture('pi-0-74-modify-other-keys-esc-cr')) - expect(modes.flags).toBe(0) - expect(modes.modifyOtherKeys).toBe(2) - - expect(resolveForPane(enter({ shiftKey: true }), modes)).toEqual({ - type: 'sendInput', - data: '\x1b[27;2;13~' - }) - expect(resolveForPane(enter({ altKey: true }), modes)).toEqual({ - type: 'sendInput', - data: '\x1b[27;3;13~' - }) - expect(resolveForPane(enter({}), modes)).toBeNull() - }) - - it('keeps kitty encoding authoritative and the legacy bytes for apps that armed nothing', () => { - const kitty = new TerminalKittyKeyboardModeTracker() - kitty.scan(readFixture('pi-0-74-late-kitty-esc-cr')) - expect(kitty.flags).toBe(7) - expect(resolveForPane(enter({ shiftKey: true }), kitty)).toEqual({ - type: 'sendInput', - data: '\x1b[13;2u' - }) - // xterm's own kitty encoder handles Alt+Enter. - expect(resolveForPane(enter({ altKey: true }), kitty)).toBeNull() - - const plain = new TerminalKittyKeyboardModeTracker() - expect(resolveForPane(enter({ shiftKey: true }), plain)).toEqual({ - type: 'sendInput', - data: '\x1b\r' - }) - expect(resolveForPane(enter({ altKey: true }), plain)).toBeNull() - }) - - it('drops the mode on disarm or terminal reset and keeps it across a snapshot', () => { - const modes = new TerminalKittyKeyboardModeTracker() - for (const disarm of ['\x1b[>4;0m', '\x1b[>4;m', '\x1b[>4m', '\x1bc']) { - modes.scan('\x1b[>4;2m') - expect(modes.modifyOtherKeys).toBe(2) - modes.scan(disarm) - expect(modes.modifyOtherKeys).toBe(0) - } - modes.scan('\x1b[>4;') - modes.scan('2m') - expect(modes.modifyOtherKeys).toBe(2) - // An older host's snapshot cannot restate the mode, so a snapshot keeps what live output proved. - modes.resetForSnapshot() - expect(modes.modifyOtherKeys).toBe(2) - modes.scanReplay('\x1b[>4;1m') - expect(modes.modifyOtherKeys).toBe(1) - modes.reset() - expect(modes.modifyOtherKeys).toBe(0) - // Other `CSI > Pp ; Pv m` resources are not modifyOtherKeys. - modes.scan('\x1b[>1;2m') - expect(modes.modifyOtherKeys).toBe(0) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-pane-spawn-placement.test.ts b/src/renderer/src/components/terminal-pane/terminal-pane-spawn-placement.test.ts deleted file mode 100644 index 332e3f2ea1e..00000000000 --- a/src/renderer/src/components/terminal-pane/terminal-pane-spawn-placement.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { TerminalPanePlacement } from '../../../../shared/workspace-layout/terminal-pane-placement' - -const TAB = { - id: 'tab-1', - ptyId: null, - worktreeId: 'wt-1', - title: 'Terminal 2', - defaultTitle: 'Terminal 2', - customTitle: 'Build', - color: '#f97316', - sortOrder: 1, - createdAt: 42, - shellOverride: 'wsl.exe', - isPinned: true -} - -vi.mock('@/store', () => ({ - useAppStore: { getState: () => ({ tabsByWorktree: { 'wt-1': [TAB] } }) } -})) -// Why: happy-dom has no canvas, so xterm cannot open; placement never touches the terminal. -vi.mock('@/lib/pane-manager/pane-lifecycle', async (importOriginal) => { - const actual: object = await importOriginal() - return { ...actual, openTerminal: vi.fn() } -}) - -const { PaneManager } = await import('@/lib/pane-manager/pane-manager') -const { completePaneSpawnPlacement } = await import('./terminal-pane-spawn-placement') - -const LEAF_A = '11111111-1111-4111-8111-111111111111' -const LEAF_B = '22222222-2222-4222-8222-222222222222' - -describe('completePaneSpawnPlacement', () => { - const root = document.createElement('div') - - afterEach(() => { - root.replaceChildren() - }) - - it('adds the tab creation fields to a new tab', () => { - const placement = completePaneSpawnPlacement( - { kind: 'new-tab' }, - { worktreeId: 'wt-1', tabId: 'tab-1', container: root } - ) - - expect(placement).toEqual({ - kind: 'new-tab', - row: { - title: 'Terminal 2', - defaultTitle: 'Terminal 2', - customTitle: 'Build', - color: '#f97316', - createdAt: 42, - shellOverride: 'wsl.exe' - } - }) - }) - - it('leaves a new tab bare when the store no longer has it', () => { - expect( - completePaneSpawnPlacement( - { kind: 'new-tab' }, - { worktreeId: 'wt-1', tabId: 'tab-gone', container: root } - ) - ).toEqual({ kind: 'new-tab' }) - }) - - it('adds the mounted tree after the split', () => { - let placement: TerminalPanePlacement | undefined - const manager = new PaneManager(root, { - linkOpenHint: () => '', - onPaneCreated: (_pane, hints) => { - placement = hints?.placement - ? completePaneSpawnPlacement(hints.placement, { - worktreeId: 'wt-1', - tabId: 'tab-1', - container: root - }) - : undefined - } - }) - const first = manager.createInitialPane({ leafId: LEAF_A }) - manager.splitPane(first.id, 'horizontal', { leafId: LEAF_B, ratio: 0.3 }) - - expect(placement).toEqual({ - kind: 'split', - parentLeafId: LEAF_A, - direction: 'horizontal', - ratio: 0.3, - proposedRoot: { - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', leafId: LEAF_A }, - second: { type: 'leaf', leafId: LEAF_B }, - ratio: 0.3 - } - }) - manager.destroy() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-webgl-diagnostics-breadcrumbs.test.ts b/src/renderer/src/components/terminal-pane/terminal-webgl-diagnostics-breadcrumbs.test.ts deleted file mode 100644 index d77f82c44ae..00000000000 --- a/src/renderer/src/components/terminal-pane/terminal-webgl-diagnostics-breadcrumbs.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { recordRendererCrashBreadcrumb } from '@/lib/crash-breadcrumb-recorder' -import { recordTerminalWebglDiagnostic } from '../../../../shared/terminal/diagnostics/terminal-webgl-diagnostics' -import { - getTerminalFreezeBreadcrumbs, - resetTerminalFreezeBreadcrumbsForTesting -} from './terminal-freeze-breadcrumbs' - -vi.mock('@/lib/crash-breadcrumb-recorder', () => ({ - recordRendererCrashBreadcrumb: vi.fn() -})) - -// Import diagnostics bootstrap to route lib-layer shared-sink WebGL crumbs into the same freeze history as delivery/visibility. -describe('WebGL diagnostics → freeze breadcrumb ring', () => { - beforeEach(() => { - resetTerminalFreezeBreadcrumbsForTesting() - vi.mocked(recordRendererCrashBreadcrumb).mockClear() - }) - - afterEach(() => { - resetTerminalFreezeBreadcrumbsForTesting() - }) - - it('routes context-loss and atlas-reset crumbs into the freeze report ring', () => { - recordTerminalWebglDiagnostic('webgl-context-loss', { paneId: 3 }) - recordTerminalWebglDiagnostic('webgl-atlas-reset', { managers: 1 }) - - const crumbs = getTerminalFreezeBreadcrumbs() - expect(crumbs.map((crumb) => crumb.kind)).toEqual(['webgl-context-loss', 'webgl-atlas-reset']) - expect(crumbs[0]?.detail).toEqual({ paneId: 3 }) - expect(crumbs[1]?.detail).toEqual({ managers: 1 }) - }) - - // Mirror into crash reports: renderer death loses the DevTools-only ring and previously hid GPU-death evidence. - it('mirrors WebGL crumbs into the crash report so a dead renderer still reports them', () => { - recordTerminalWebglDiagnostic('webgl-context-loss', { paneId: 3 }) - - expect(recordRendererCrashBreadcrumb).toHaveBeenCalledWith('terminal_webgl_diagnostic', { - kind: 'webgl-context-loss', - paneId: 3 - }) - }) - - it('mirrors detail-less crumbs without inventing fields', () => { - recordTerminalWebglDiagnostic('webgl-context-restore') - - expect(recordRendererCrashBreadcrumb).toHaveBeenCalledWith('terminal_webgl_diagnostic', { - kind: 'webgl-context-restore' - }) - }) - - it('bounds atlas mismatch storm IPC while retaining the local occurrence count', () => { - vi.useFakeTimers() - try { - for (let mismatch = 0; mismatch < 10_000; mismatch++) { - recordTerminalWebglDiagnostic('atlas-font-probe-mismatch', { - desired: '550', - actual: '700 14px Menlo' - }) - } - - expect(recordRendererCrashBreadcrumb).toHaveBeenCalledTimes(1) - expect(getTerminalFreezeBreadcrumbs()).toEqual([ - expect.objectContaining({ kind: 'atlas-font-probe-mismatch', repeats: 10_000 }) - ]) - - vi.advanceTimersByTime(30_000) - recordTerminalWebglDiagnostic('atlas-font-probe-mismatch', { - desired: '550', - actual: '700 14px Menlo' - }) - expect(recordRendererCrashBreadcrumb).toHaveBeenLastCalledWith( - 'terminal_webgl_diagnostic', - expect.objectContaining({ rendererSuppressedSinceLast: 9_999 }) - ) - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/renderer/src/components/terminal-pane/use-layout-owner-pane-tree.test.ts b/src/renderer/src/components/terminal-pane/use-layout-owner-pane-tree.test.ts deleted file mode 100644 index a1e5e804bcf..00000000000 --- a/src/renderer/src/components/terminal-pane/use-layout-owner-pane-tree.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -// @vitest-environment happy-dom -import { act, renderHook } from '@testing-library/react' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { TerminalLayoutSnapshot } from '../../../../shared/workspace-layout/terminal-tab-types' -import { - _resetLayoutOwnerPaneIntentsForTests, - holdTabPaneTree, - onTabPaneTreeRedraw -} from '@/runtime/layout-owner-pane-intents' -import type { TerminalPaneCloseController } from './use-terminal-pane-close-actions' - -const reconcile = vi.hoisted(() => vi.fn(() => false)) -vi.mock('./terminal-pane-frame-reconciliation', () => ({ - reconcileMountedPanesToLayout: reconcile -})) - -const pairedServer = vi.hoisted(() => ({ mirrors: false })) -vi.mock('@/store', () => ({ useAppStore: { getState: () => ({}) } })) -vi.mock('@/runtime/paired-server-workspace', () => ({ - pairedServerMirrors: () => () => pairedServer.mirrors -})) - -const { useLayoutOwnerPaneTree } = await import('./use-layout-owner-pane-tree') - -const layout = (expandedLeafId: string | null): TerminalLayoutSnapshot => ({ - root: { type: 'leaf', leafId: 'leaf-1' }, - activeLeafId: 'leaf-1', - expandedLeafId -}) - -function controllerWith(restoredLayout: TerminalLayoutSnapshot): TerminalPaneCloseController { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the hook reads only these fields. - return { - tabId: 'tab-1', - worktreeId: 'wt-1', - restoredLayout, - isolatedPaneKey: null, - expandedPaneIdRef: { current: null }, - managerRef: { current: {} }, - closePaneLocally: vi.fn(), - onCloseTab: vi.fn(), - persistLayoutSnapshot: vi.fn() - } as unknown as TerminalPaneCloseController -} - -describe('useLayoutOwnerPaneTree', () => { - beforeEach(() => { - _resetLayoutOwnerPaneIntentsForTests() - reconcile.mockClear() - pairedServer.mirrors = false - }) - - it('leaves a paired server’s tab to its host, even before a remote terminal binds', () => { - pairedServer.mirrors = true - renderHook(() => useLayoutOwnerPaneTree(controllerWith(layout(null)))) - expect(reconcile).not.toHaveBeenCalled() - }) - - it('waits while the window’s own pane command holds the tab, then draws main’s tree', () => { - const release = holdTabPaneTree('tab-1') - renderHook(() => useLayoutOwnerPaneTree(controllerWith(layout(null)))) - expect(reconcile).not.toHaveBeenCalled() - - act(() => release()) - - expect(reconcile).toHaveBeenCalledOnce() - }) - - it('asks for main’s tree again when a zoomed pane collapses', () => { - const redraws = vi.fn() - onTabPaneTreeRedraw(redraws) - const { rerender } = renderHook( - ({ snapshot }) => useLayoutOwnerPaneTree(controllerWith(snapshot)), - { - initialProps: { snapshot: layout('leaf-1') } - } - ) - expect(reconcile).toHaveBeenLastCalledWith(expect.objectContaining({ isExpanded: true })) - expect(redraws).not.toHaveBeenCalled() - - rerender({ snapshot: layout(null) }) - - expect(redraws).toHaveBeenCalledWith('tab-1') - expect(reconcile).toHaveBeenLastCalledWith(expect.objectContaining({ isExpanded: false })) - }) -}) diff --git a/src/renderer/src/components/use-terminal-editor-close-queue.reveal.test.tsx b/src/renderer/src/components/use-terminal-editor-close-queue.reveal.test.tsx deleted file mode 100644 index a5226afd559..00000000000 --- a/src/renderer/src/components/use-terminal-editor-close-queue.reveal.test.tsx +++ /dev/null @@ -1,104 +0,0 @@ -// @vitest-environment happy-dom - -import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' -import type * as EditorAutosaveModule from './editor/autosave/editor-autosave' - -type FakeOpenFile = { id: string; worktreeId: string; isDirty: boolean; relativePath: string } -const store = vi.hoisted((): { openFiles: FakeOpenFile[]; activeWorktreeId: string | null } => ({ - openFiles: [], - activeWorktreeId: 'wt-main' -})) -const revealFloatingWorkspacePanel = vi.hoisted(() => vi.fn()) - -vi.mock('../store', () => ({ - useAppStore: { - getState: () => ({ - ...store, - editorBufferIdOf: {}, - editorBufferViews: {}, - setActiveWorktree, - markFileDirty: vi.fn(), - clearEditorDraft: vi.fn(), - closeFile - }), - subscribe: () => () => {} - } -})) -vi.mock('@/lib/floating-workspace-panel-reveal', () => ({ revealFloatingWorkspacePanel })) -vi.mock('./terminal/window-close-running-work', () => ({ assessWindowCloseRunningWork: vi.fn() })) -vi.mock('./window-close-request-coordinator', () => ({ - runWithWindowCloseCheckpointScope: (fn: () => unknown) => fn() -})) -vi.mock('@/lib/shutdown-checkpoint-failure-toast', () => ({ - showShutdownCheckpointFailureToast: vi.fn() -})) -vi.mock('./editor/autosave/editor-autosave', async (importActual) => ({ - ...(await importActual()), - requestEditorSaveQuiesce: vi.fn(async () => () => {}) -})) - -const { useTerminalEditorCloseFoundation } = await import('./use-terminal-editor-close-foundation') -const { useTerminalEditorCloseQueue } = await import('./use-terminal-editor-close-queue') -const { useTerminalEditorCloseDialogActions } = - await import('./use-terminal-editor-close-dialog-actions') -const { requestEditorFileClose } = await import('./editor/autosave/editor-autosave') - -const setActiveWorktree = vi.fn() -const setActiveFile = vi.fn() -const setActiveTabType = vi.fn() -const closeFile = vi.fn((fileId: string) => { - store.openFiles = store.openFiles.filter((file) => file.id !== fileId) -}) - -type Base = Parameters[0] - -function mountCloseQueue() { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the close hooks read only these projection fields; the rest of the workspace projection is unused here. - const base = { - activeWorktreeId: store.activeWorktreeId, - openFiles: store.openFiles, - closeFile, - markFileDirty: vi.fn(), - setActiveFile, - setActiveTabType, - setActiveWorktree - } as unknown as Base - return renderHook(() => { - const foundation = Object.assign({ ...base }, useTerminalEditorCloseFoundation(base)) - const queue = Object.assign(foundation, useTerminalEditorCloseQueue(foundation)) - return Object.assign(queue, useTerminalEditorCloseDialogActions(queue)) - }) -} - -function dirtyFile(id: string, worktreeId: string): FakeOpenFile { - return { id, worktreeId, isDirty: true, relativePath: `${id}.md` } -} - -// Reveal unsaved floating notes in their own panel without taking over the main window’s workspace. -describe('unsaved-changes prompt for a closing file', () => { - beforeEach(() => { - vi.clearAllMocks() - store.activeWorktreeId = 'wt-main' - }) - afterEach(() => cleanup()) - - // Why a later close of the same file: a cancelled reaction left behind would fire on it. - it('drops the close reaction when the prompt is cancelled', async () => { - vi.useFakeTimers() - store.openFiles = [dirtyFile('note', FLOATING_TERMINAL_WORKTREE_ID)] - const onClosed = vi.fn() - const { result } = mountCloseQueue() - act(() => requestEditorFileClose('note', { onClosed })) - act(() => result.current.handleSaveDialogCancel()) - act(() => vi.runAllTimers()) - - act(() => requestEditorFileClose('note')) - await act(() => result.current.handleSaveDialogDiscard()) - - expect(closeFile).toHaveBeenCalledWith('note') - expect(onClosed).not.toHaveBeenCalled() - vi.useRealTimers() - }) -}) diff --git a/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-browse-state.test.tsx b/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-browse-state.test.tsx index 077d4349293..d60b8ecc216 100644 --- a/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-browse-state.test.tsx +++ b/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-browse-state.test.tsx @@ -9,7 +9,7 @@ import { resetWorkspaceCleanupBrowsePersistTimer } from '@/store/slices/workspace-cleanup-browse' import { createDefaultWorkspaceCleanupBrowseState } from '../../../../shared/workspace-cleanup/workspace-cleanup-browse-state' -import { listAppliedWorkspaceCleanupFilters } from '../../../../shared/workspace-cleanup/workspace-cleanup-applied-filters' + import { useWorkspaceCleanupBrowseState, type WorkspaceCleanupBrowseController @@ -78,40 +78,4 @@ describe('useWorkspaceCleanupBrowseState', () => { expect(git.minAhead).toBe(2) expect(git.branchQuery).toBe('release') }) - - it('flips sort direction against the latest state, not the rendered snapshot', () => { - const controller = mountController() - - act(() => { - controller.current!.toggleSortField('size') - controller.current!.toggleSortField('size') - }) - - expect(store.getState().workspaceCleanupBrowse.sort).toEqual({ - field: 'size', - direction: 'desc' - }) - }) - - it('keeps a cleared chip cleared when a facet patch lands in the same tick', () => { - const controller = mountController() - act(() => controller.current!.patchFilters('activity', { idleMinDays: 20 })) - - const format = new Proxy({}, { get: () => () => 'chip' }) as Parameters< - typeof listAppliedWorkspaceCleanupFilters - >[1] - const chip = listAppliedWorkspaceCleanupFilters( - store.getState().workspaceCleanupBrowse.filters, - format - ).find((a) => a.id === 'activity.idleMinDays')! - - act(() => { - controller.current!.replaceFilters(chip.clear) - controller.current!.patchFilters('git', { states: ['dirty'] }) - }) - - const filters = store.getState().workspaceCleanupBrowse.filters - expect(filters.activity.idleMinDays).toBeNull() - expect(filters.git.states).toEqual(['dirty']) - }) }) diff --git a/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-row-order.test.ts b/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-row-order.test.ts index b837f4eb708..aa2c8d9ce9b 100644 --- a/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-row-order.test.ts +++ b/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-row-order.test.ts @@ -2,12 +2,7 @@ import { renderHook } from '@testing-library/react' import { describe, expect, it } from 'vitest' -import { - arrangeWorkspaceCleanupRowsByFrozenOrder, - createWorkspaceCleanupFrozenRowOrder, - extendWorkspaceCleanupFrozenRowOrder, - useWorkspaceCleanupRowOrder -} from './use-workspace-cleanup-row-order' +import { useWorkspaceCleanupRowOrder } from './use-workspace-cleanup-row-order' import type { WorkspaceCleanupSortState } from '../../../../shared/workspace-cleanup/workspace-cleanup-filter-model' type Row = { worktreeId: string } @@ -17,42 +12,6 @@ const ids = (rows: readonly Row[]): string[] => rows.map((entry) => entry.worktr const ascending: WorkspaceCleanupSortState = { field: 'name', direction: 'asc' } describe('workspace cleanup streaming row order', () => { - it('keeps existing rows in their frozen slots when streamed values would resort them', () => { - const order = createWorkspaceCleanupFrozenRowOrder([row('a'), row('b'), row('c')], 'name:asc') - - const arranged = arrangeWorkspaceCleanupRowsByFrozenOrder([row('c'), row('a'), row('b')], order) - - expect(ids(arranged)).toEqual(['a', 'b', 'c']) - }) - - it('holds slots for rows a filter temporarily hides', () => { - const order = createWorkspaceCleanupFrozenRowOrder([row('a'), row('b'), row('c')], 'name:asc') - - expect(ids(arrangeWorkspaceCleanupRowsByFrozenOrder([row('c'), row('a')], order))).toEqual([ - 'a', - 'c' - ]) - expect( - ids(arrangeWorkspaceCleanupRowsByFrozenOrder([row('c'), row('b'), row('a')], order)) - ).toEqual(['a', 'b', 'c']) - }) - - it('grows the frozen order from empty during a cold-start stream', () => { - const order = createWorkspaceCleanupFrozenRowOrder([], 'name:asc') - const firstRows = [row('b'), row('d')] - - expect(ids(arrangeWorkspaceCleanupRowsByFrozenOrder(firstRows, order))).toEqual(['b', 'd']) - const extendedOrder = extendWorkspaceCleanupFrozenRowOrder(firstRows, order) - expect( - ids( - arrangeWorkspaceCleanupRowsByFrozenOrder( - [row('a'), row('b'), row('c'), row('d')], - extendedOrder - ) - ) - ).toEqual(['b', 'd', 'a', 'c']) - }) - it('commits appended positions after each rendered stream tick', () => { const view = renderHook( ({ rows, streaming }: { rows: readonly Row[]; streaming: boolean }) => diff --git a/src/renderer/src/hooks/automation-dispatch-interrupted-turn.test.ts b/src/renderer/src/hooks/automation-dispatch-interrupted-turn.test.ts index e360a46340a..a91c35f2a98 100644 --- a/src/renderer/src/hooks/automation-dispatch-interrupted-turn.test.ts +++ b/src/renderer/src/hooks/automation-dispatch-interrupted-turn.test.ts @@ -58,15 +58,4 @@ describe('automation dispatch completion for an interrupted turn', () => { ) expect(finalizeTerminalOwnership).not.toHaveBeenCalled() }) - - it('still records an uninterrupted turn as completed', async () => { - const completion = await createCompletion() - await completion.settlePendingAfterDispatch() - completion.handleAgentDone({}) - await vi.waitFor(() => expect(finalizeTerminalOwnership).toHaveBeenCalled()) - - expect(markDispatchResult).toHaveBeenCalledWith( - expect.objectContaining({ status: 'completed', error: null }) - ) - }) }) diff --git a/src/renderer/src/lib/automation-terminal-bind-layout-owner.test.ts b/src/renderer/src/lib/automation-terminal-bind-layout-owner.test.ts deleted file mode 100644 index 6d091dc129b..00000000000 --- a/src/renderer/src/lib/automation-terminal-bind-layout-owner.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as AgentStatusModule from '@/lib/agent-status' -import { createTestStore, makeWorktree, seedStore } from '@/store/slices/store-test-helpers' -import { createStoreCascadesMockApi } from '@/store/slices/store-cascades-test-harness' -import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { LayoutApplyParams } from '../../../shared/rpc-contract/workspace-layout-params' -import { bindAutomationTerminal } from './automation-terminal-ownership' - -const mocks = vi.hoisted(() => { - const storeRef: { current: unknown } = { current: null } - return { - storeRef, - callRuntimeRpc: vi.fn(async (_target: unknown, _method: string, _params: unknown) => ({ - ok: true, - result: {} - })) - } -}) - -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('@/runtime/runtime-rpc-client', () => ({ callRuntimeRpc: mocks.callRuntimeRpc })) -vi.mock('@/store', () => ({ - get useAppStore() { - return mocks.storeRef.current - } -})) -vi.mock('sonner', () => ({ - toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } -})) -vi.mock('@/lib/agent-status', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) } -}) - -createStoreCascadesMockApi() - -const WT = 'repo1::/path/wt1' -const LEAF = '11111111-1111-4111-8111-111111111111' - -let store: ReturnType - -beforeEach(() => { - mocks.callRuntimeRpc.mockClear() - store = createTestStore() - mocks.storeRef.current = store - seedStore(store, { - worktreesByRepo: { repo1: [makeWorktree({ id: WT, repoId: 'repo1', path: '/path/wt1' })] }, - activeWorktreeId: WT - }) -}) - -describe('a background agent tab in a layout-owner build', () => { - it('binds the one-pane tree main made the tab with, so the bind changes no pane tree', () => { - // As adoptAgentBackgroundSessionTab: the tab is made under its terminal's pane id. - const tab = store.getState().createTab(WT, undefined, undefined, { - id: 'tab-run', - initialLeafId: LEAF, - initialPtyId: 'pty-run', - activate: false, - recordInteraction: false - }) - const [create] = mocks.callRuntimeRpc.mock.calls.map( - ([, , params]) => LayoutApplyParams.parse(params).command - ) - - bindAutomationTerminal(tab, makePaneKey(tab.id, LEAF), 'pty-run', 'environment') - - expect(create).toEqual(expect.objectContaining({ type: 'createTerminalTab', leafId: LEAF })) - expect(store.getState().terminalLayoutsByTabId[tab.id]?.root).toEqual({ - type: 'leaf', - leafId: LEAF - }) - // The bind sends nothing more: main already holds this tree. - expect(mocks.callRuntimeRpc).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/renderer/src/lib/browser-workspace-tab-activation.test.ts b/src/renderer/src/lib/browser-workspace-tab-activation.test.ts deleted file mode 100644 index 40516fef2c2..00000000000 --- a/src/renderer/src/lib/browser-workspace-tab-activation.test.ts +++ /dev/null @@ -1,148 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, expect, it } from 'vitest' -import { useAppStore } from '@/store' -import type { Tab } from '../../../shared/tab-types' -import type { Worktree } from '../../../shared/worktree/types' -import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' -import { folderWorkspaceKey } from '../../../shared/workspace-scope' -import { getActivatableBrowserWorkspaceTab } from './browser-workspace-tab-activation' - -const initialState = useAppStore.getInitialState() -afterEach(() => useAppStore.setState(initialState, true)) - -function makeWorktree(overrides: Partial & Pick): Worktree { - return { - repoId: 'repo', - path: '/workspace', - head: '', - branch: 'main', - isBare: false, - isMainWorktree: true, - displayName: 'Workspace', - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - ...overrides - } -} - -const browserTab: Tab = { - id: 'unified-browser', - entityId: 'workspace', - groupId: 'group', - worktreeId: 'wt', - contentType: 'browser', - label: 'Browser', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 0 -} - -function seedState(worktreesByRepo: Record, tab: Tab): void { - useAppStore.setState( - { ...initialState, worktreesByRepo, unifiedTabsByWorktree: { wt: [tab] } }, - true - ) -} - -function makeFolderWorkspace(executionHostId: 'local' | 'ssh:remote'): FolderWorkspace { - return { - id: 'shared-folder', - projectGroupId: 'group', - name: 'Shared folder', - folderPath: '/workspace', - executionHostId, - linkedTask: null, - comment: '', - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - createdAt: 0, - updatedAt: 0 - } -} - -it('refuses a hostless browser tab for a remote worktree whose ID also exists locally', () => { - seedState( - { - local: [makeWorktree({ id: 'wt' })], - remote: [makeWorktree({ id: 'wt', repoId: 'repo-remote', hostId: 'ssh:remote' })] - }, - browserTab - ) - - expect( - getActivatableBrowserWorkspaceTab({ - worktreeId: 'wt', - workspaceId: 'workspace', - executionHostId: 'ssh:remote' - }) - ).toBeNull() -}) - -it('refuses hostless activation when the caller omits a host for an ambiguous worktree id', () => { - seedState( - { - local: [makeWorktree({ id: 'wt' })], - remote: [makeWorktree({ id: 'wt', repoId: 'repo-remote', hostId: 'ssh:remote' })] - }, - { ...browserTab, executionHostId: 'ssh:remote' } - ) - - expect( - getActivatableBrowserWorkspaceTab({ worktreeId: 'wt', workspaceId: 'workspace' }) - ).toBeNull() -}) - -it('accepts a hostless browser tab when the worktree ID is unambiguous', () => { - seedState({ remote: [makeWorktree({ id: 'wt', hostId: 'ssh:remote' })] }, browserTab) - - expect( - getActivatableBrowserWorkspaceTab({ - worktreeId: 'wt', - workspaceId: 'workspace', - executionHostId: 'ssh:remote' - }) - ).toEqual(browserTab) - - useAppStore.setState({ - unifiedTabsByWorktree: { - wt: [browserTab], - other: [{ ...browserTab, worktreeId: 'other', contentType: 'terminal', entityId: 'terminal' }] - } - }) - expect( - getActivatableBrowserWorkspaceTab({ - worktreeId: 'wt', - workspaceId: 'workspace', - executionHostId: 'ssh:remote' - }) - ).toBeNull() -}) - -it('includes folder workspaces when rejecting ambiguous hostless activation', () => { - const worktreeId = folderWorkspaceKey('shared-folder') - useAppStore.setState( - { - ...initialState, - folderWorkspaces: [makeFolderWorkspace('local'), makeFolderWorkspace('ssh:remote')], - worktreesByRepo: {}, - unifiedTabsByWorktree: { - [worktreeId]: [{ ...browserTab, worktreeId, executionHostId: 'ssh:remote' }] - } - }, - true - ) - - expect(getActivatableBrowserWorkspaceTab({ worktreeId, workspaceId: 'workspace' })).toBeNull() -}) diff --git a/src/renderer/src/lib/default-terminal-tabs-applied-persist.test.ts b/src/renderer/src/lib/default-terminal-tabs-applied-persist.test.ts deleted file mode 100644 index e31a5ec8d5f..00000000000 --- a/src/renderer/src/lib/default-terminal-tabs-applied-persist.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import { preserveRuntimeAuthoredWorkspaceSessionFields } from '../../../main/persistence/runtime-authored-workspace-session-fields' -import { parseWorkspaceSession } from '../../../shared/workspace-session/workspace-session-schema' -import { useAppStore, type AppState } from '@/store' -import { applyDefaultTerminalTabs } from './worktree-default-terminal-tabs' -import { - createSessionWriteSubscriber, - type WorkspaceSessionWrite -} from './session-write-subscriber' -import { createTestStore, makeWorktree, seedStore } from '@/store/slices/store-test-helpers' - -let initialState: AppState - -const WORKTREE_ID = 'repo1::/wt-1' -const DEFAULT_TABS = { - runCommands: false, - tabs: [{ title: 'Claude' }] -} - -describe('defaultTerminalTabsAppliedByWorktreeId persist round-trip', () => { - beforeEach(() => { - initialState = useAppStore.getState() - vi.useFakeTimers() - }) - - afterEach(() => { - vi.useRealTimers() - useAppStore.setState(initialState, true) - }) - - it('keeps the marker through mark, persist patch, omitted snapshot, and hydration', () => { - const persist = vi.fn<(payload: WorkspaceSessionWrite) => void>() - const cleanup = createSessionWriteSubscriber({ store: useAppStore, persist }) - - useAppStore.setState({ workspaceSessionReady: true, hydrationSucceeded: true }) - vi.advanceTimersByTime(200) - persist.mockClear() - - useAppStore.getState().markDefaultTerminalTabsApplied(WORKTREE_ID) - vi.advanceTimersByTime(200) - - expect(persist.mock.calls[0][0].patch.defaultTerminalTabsAppliedByWorktreeId).toEqual({ - [WORKTREE_ID]: true - }) - - const patched = { - ...getDefaultWorkspaceSession(), - ...persist.mock.calls[0][0].patch - } - // Persist snapshots omit this write-once slice (empty payload / renderer never mentioned it). - const omittedSnapshot = getDefaultWorkspaceSession() - const preserved = preserveRuntimeAuthoredWorkspaceSessionFields(omittedSnapshot, patched) - const parsed = parseWorkspaceSession(JSON.parse(JSON.stringify(preserved))) - expect(parsed.ok).toBe(true) - if (!parsed.ok) { - return - } - - const store = createTestStore() - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: WORKTREE_ID, repoId: 'repo1', path: '/wt-1' })] - } - }) - store.getState().hydrateWorkspaceSession(parsed.value) - - expect(store.getState().defaultTerminalTabsAppliedByWorktreeId[WORKTREE_ID]).toBe(true) - expect( - applyDefaultTerminalTabs( - store.getState(), - WORKTREE_ID, - undefined, - undefined, - undefined, - DEFAULT_TABS, - undefined, - undefined - ) - ).toBeNull() - expect(store.getState().tabsByWorktree[WORKTREE_ID]).toBeUndefined() - cleanup() - }) - - it('does not drop in-memory markers when hydration omits the map', () => { - const store = createTestStore() - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: WORKTREE_ID, repoId: 'repo1', path: '/wt-1' })] - } - }) - store.getState().markDefaultTerminalTabsApplied(WORKTREE_ID) - - store.getState().hydrateWorkspaceSession({ - activeRepoId: 'repo1', - activeWorktreeId: WORKTREE_ID, - activeTabId: null, - terminalLayoutsByTabId: {}, - tabsByWorktree: {} - }) - - expect(store.getState().defaultTerminalTabsAppliedByWorktreeId[WORKTREE_ID]).toBe(true) - expect( - applyDefaultTerminalTabs( - store.getState(), - WORKTREE_ID, - undefined, - undefined, - undefined, - DEFAULT_TABS, - undefined, - undefined - ) - ).toBeNull() - }) -}) diff --git a/src/renderer/src/store/slices/worktrees/teardown/worktree-delete-state.test.ts b/src/renderer/src/store/slices/worktrees/teardown/worktree-delete-state.test.ts index 9e023399ef1..2ae6f103c88 100644 --- a/src/renderer/src/store/slices/worktrees/teardown/worktree-delete-state.test.ts +++ b/src/renderer/src/store/slices/worktrees/teardown/worktree-delete-state.test.ts @@ -23,40 +23,6 @@ beforeEach(() => { const ID = 'repo1::/path/wt' describe('worktree delete-state keying', () => { - it('shows a local-qualified delete on the card of a row stored without a host', () => { - const store = createTestStore() - const card = makeWorktree({ id: ID, repoId: 'repo1' }) - store.setState({ worktreesByRepo: { repo1: [card] } }) - - store.getState().markWorktreesQueuedForDeletion([{ id: ID, hostId: 'local' }]) - expect( - getDeleteStateForWorktreeHost(card, store.getState().deleteStateByWorktreeId) - ).toMatchObject({ isDeleting: true, phase: 'queued' }) - - store.getState().markWorktreesDeleting([{ id: ID, hostId: 'local' }]) - expect( - getDeleteStateForWorktreeHost(card, store.getState().deleteStateByWorktreeId) - ).toMatchObject({ isDeleting: true, phase: 'deleting' }) - - store.getState().clearWorktreeDeleteState(ID, 'local') - expect(store.getState().deleteStateByWorktreeId).toEqual({}) - }) - - it('keeps the same id on two hosts in separate delete states', () => { - const store = createTestStore() - const local = makeWorktree({ id: ID, repoId: 'repo1' }) - const remote = makeWorktree({ id: ID, repoId: 'repo1', hostId: 'ssh:host-b' }) - store.setState({ worktreesByRepo: { repo1: [local, remote] } }) - - store.getState().markWorktreesQueuedForDeletion([{ id: ID, hostId: 'ssh:host-b' }]) - const states = store.getState().deleteStateByWorktreeId - expect(getDeleteStateForWorktreeHost(remote, states)?.isDeleting).toBe(true) - expect(getDeleteStateForWorktreeHost(local, states)).toBeUndefined() - - store.getState().clearWorktreeDeleteState(ID, 'ssh:host-b') - expect(store.getState().deleteStateByWorktreeId).toEqual({}) - }) - it('shows a local-qualified removal failure on the card of a row stored without a host', async () => { const store = createTestStore() const card = makeWorktree({ id: ID, repoId: 'repo1', path: '/path/wt' })