test: remove 140 low-value cases and 49 suites (#34062)

* test: remove 140 low-value cases and redundant browser probes

* fix: remove unused upstream chat menu import

* test: pin the host-split layout fixture branch

---------

Co-authored-by: Orca Test Audit <test-audit@stably.ai>
Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-10-26 15:16:27 -07:00
committed by GitHub
co-authored by Orca Test Audit OrcaWin
parent 7423c8c6e1
commit ad2156c358
76 changed files with 23 additions and 2616 deletions
-1
View File
@@ -1090,7 +1090,6 @@ jobs:
--no-file-parallelism
src/main/browser/browser-client-page-renderer-lifecycle.electron.test.ts
src/main/browser/browser-route-webrtc-egress.electron.test.ts
src/main/browser/browser-route-h3-egress.electron.test.ts
src/main/persistence/profile-state/profile-state-writer-stall.electron.test.ts
src/main/browser/popup-origin-chrome.electron.test.ts
src/main/browser/browser-link-materialization.electron.test.ts
-1
View File
@@ -1194,7 +1194,6 @@
1 test-timeout-needs-reason:src/main/browser/agent-browser-bridge-raw-process.test.ts
1 test-timeout-needs-reason:src/main/browser/browser-client-page-renderer-lifecycle.electron.test.ts
1 test-timeout-needs-reason:src/main/browser/browser-find-frame-traversal.electron.test.ts
1 test-timeout-needs-reason:src/main/browser/browser-route-h3-egress.electron.test.ts
1 test-timeout-needs-reason:src/main/browser/browser-route-webrtc-egress.electron.test.ts
1 test-timeout-needs-reason:src/main/browser/browser-session-ua-cloudflare-live.electron.test.ts
2 test-timeout-needs-reason:src/main/browser/browser-session-ua-wire-identity-cross-context.electron.test.ts
+16 -51
View File
@@ -7628,25 +7628,23 @@
"providers": ["remote-runtime", "ssh", "wsl"],
"coveredPlatforms": ["macos", "linux"],
"coveredProviders": ["ssh", "remote-runtime"],
"coverageNotes": "Deterministic main-process tests cover versioned delimiter-safe aggregate partition derivation, path-safe opaque names, durable collision metadata, oversized or corrupt metadata refusal, missing-sidecar Chromium-data refusal, bounded binding/live-page admission, immediate SOCKS5 setup with Chromium loopback bypass disabled, inherited-connection closure, exact proxy verification before allowlisting, concurrent setup coalescing, live proxy-retarget refusal, token-safe page replacement, existing browser-profile policy installation, active Orca-profile storage scoping, blank-only initial attachment, arbitrary initial-navigation denial, and fail-closed per-guest WebRTC policy through delayed or failed cleanup. The production client-page executor prepares, registers, and grants the exact route page. Archived standalone Electron experiments measured TCP routing and a forced persisted-worker wake using fixture-owned proxy setup; they did not exercise production route preparation and are no longer current test coverage. A separate capture proves the protected guest sends zero direct STUN packets. A further capture proves non-WebRTC UDP is also contained: a WebTransport session and a fetch forced onto QUIC both reach the desktop directly in the control arm and emit zero datagrams through the route partition, and the shipped disable-features list hides the Direct Sockets constructors whose mere construction kills a control-arm renderer. An archived DNS-prefetch experiment observed an accepted Electron 43 residual: prefetched hostnames resolved on the desktop outside the tunnel. It asserted the leak and was removed; current production-path TCP, persisted-worker, and DNS-prefetch egress coverage remains incomplete. Network-service restart and WSL provider journeys remain uncovered. Four Linux Docker SSH browser baseline scenarios passed: direct-host routing, unavailable-host local escape, forwarding refusal, and paired client-hosted reconnect. All four scenarios subsequently passed three repetitions each (12 passes, no skips or retries) in Linux CI run 34040309638, with unchanged assertions and timeouts.",
"coverageNotes": "Deterministic main-process tests cover versioned delimiter-safe aggregate partition derivation, path-safe opaque names, durable collision metadata, oversized or corrupt metadata refusal, missing-sidecar Chromium-data refusal, bounded binding/live-page admission, immediate SOCKS5 setup with Chromium loopback bypass disabled, inherited-connection closure, exact proxy verification before allowlisting, concurrent setup coalescing, live proxy-retarget refusal, token-safe page replacement, existing browser-profile policy installation, active Orca-profile storage scoping, blank-only initial attachment, arbitrary initial-navigation denial, and fail-closed per-guest WebRTC policy through delayed or failed cleanup. The production client-page executor prepares, registers, and grants the exact route page. Archived standalone Electron experiments measured TCP routing and a forced persisted-worker wake using fixture-owned proxy setup; they did not exercise production route preparation and are no longer current test coverage. A separate capture proves the protected guest sends zero direct STUN packets. An archived standalone H3 experiment measured WebTransport and forced-QUIC controls through fixture-owned proxy setup and checked the shipped Direct Sockets feature list. It did not exercise Orca route preparation or admission and is no longer current product coverage. An archived DNS-prefetch experiment observed an accepted Electron 43 residual: prefetched hostnames resolved on the desktop outside the tunnel. It asserted the leak and was removed; current production-path TCP, persisted-worker, and DNS-prefetch egress coverage remains incomplete. Network-service restart and WSL provider journeys remain uncovered. Four Linux Docker SSH browser baseline scenarios passed: direct-host routing, unavailable-host local escape, forwarding refusal, and paired client-hosted reconnect. All four scenarios subsequently passed three repetitions each (12 passes, no skips or retries) in Linux CI run 34040309638, with unchanged assertions and timeouts.",
"motivatingLinks": [
"https://linear.app/stably/issue/STA-4150/refactor-remote-browser-to-client-hosted-electron-webviews",
"https://github.com/stablyai/orca/actions/runs/34039986047",
"https://github.com/stablyai/orca/actions/runs/34040309638"
],
"invariant": "A client-hosted partition is derived only in main from stable Orca-profile, browser-profile, authority-connection, and execution-host identities. Raw identities and individually linkable component hashes never enter its path-safe partition name. Durable binding metadata must match and precede Chromium partition data before reuse. One live partition never changes execution host or proxy endpoint. Fixed SOCKS5 setup starts immediately after Session creation, before policy installation can yield or a persisted worker is awakened; no partition enters the webview allowlist until browser policy is installed, inherited connections are closed, and resolveProxy returns exactly that one listener. Initial route-partition attachment is blank-only. Its exact WebContents is quarantined before applying non-proxied WebRTC denial and remains navigation- and popup-denied if policy application or cleanup fails. Distinct live partitions, retained logical page generations, durable bindings, and binding-file reads remain bounded. No UDP transport a route-partition page can reach — WebRTC, WebTransport, or forced QUIC — emits a datagram to the desktop, the Direct Sockets constructors stay absent from every guest so no page can kill its renderer, and the process never enables a DoH host-resolver mode.",
"oracle": "Derive two delimiter-adversarial identities and require distinct full-digest path-safe partitions with no raw IDs or component hashes. Persist one binding, reload it, and reject replacement, malformed or oversized state, Chromium data without matching metadata, and the 513th binding. Prepare one partition and require setProxy with <-loopback> to be invoked immediately after getSession and before policy setup, then closeAllConnections and exact SOCKS5 resolveProxy while isAllowedPartition remains false; only then may it become live. Reject DIRECT, endpoint retargeting, and capacity overflow. Require quarantine before disable_non_proxied_udp and admission; under real Electron require the unprotected control to emit STUN and the protected guest to emit zero direct UDP packets. Under real Electron require a direct control to emit WebTransport and forced-QUIC datagrams and the SOCKS partition to emit none, require an explicitly enabled Direct Sockets control to expose the constructors and die on construction, and require the shipped disable-features list to leave them undefined with the renderer alive.",
"oracle": "Derive two delimiter-adversarial identities and require distinct full-digest path-safe partitions with no raw IDs or component hashes. Persist one binding, reload it, and reject replacement, malformed or oversized state, Chromium data without matching metadata, and the 513th binding. Prepare one partition and require setProxy with <-loopback> to be invoked immediately after getSession and before policy setup, then closeAllConnections and exact SOCKS5 resolveProxy while isAllowedPartition remains false; only then may it become live. Reject DIRECT, endpoint retargeting, and capacity overflow. Require quarantine before disable_non_proxied_udp and admission; under real Electron require the unprotected control to emit STUN and the protected guest to emit zero direct UDP packets.",
"commands": [
"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/browser-route-identity.test.ts src/main/browser/browser-route-partition-binding-store.test.ts src/main/browser/browser-route-session-registry.test.ts src/main/browser/browser-session-registry.test.ts src/main/browser/browser-session-startup.test.ts src/main/window/createMainWindow.test.ts",
"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/browser-route-webcontents-registry.test.ts src/main/browser/browser-route-webrtc-egress.electron.test.ts",
"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/browser-route-h3-egress.electron.test.ts"
"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/browser-route-webcontents-registry.test.ts src/main/browser/browser-route-webrtc-egress.electron.test.ts"
],
"testFiles": [
"src/main/browser/browser-route-identity.test.ts",
"src/main/browser/browser-route-partition-binding-store.test.ts",
"src/main/browser/browser-route-session-registry.test.ts",
"src/main/browser/browser-route-webrtc-egress.electron.test.ts",
"src/main/browser/browser-route-h3-egress.electron.test.ts",
"src/main/browser/browser-route-webcontents-registry.test.ts",
"src/main/browser/browser-session-registry.test.ts",
"src/main/browser/browser-session-startup.test.ts",
@@ -7690,16 +7688,6 @@
"disable_non_proxied_udp leaves the exact guest with zero direct UDP packets"
]
},
{
"file": "src/main/browser/browser-route-h3-egress.electron.test.ts",
"assertions": [
"the direct control reaches a WebTransport endpoint over UDP and the route partition sends zero datagrams",
"a fetch forced onto QUIC by --origin-to-force-quic-on emits UDP directly and zero through the route partition",
"an explicit --enable-features exposes the Direct Sockets constructors in the control arm",
"constructing a TCPSocket in the control arm kills the guest renderer",
"the shipped disable-features list leaves every Direct Sockets constructor undefined and the renderer alive"
]
},
{
"file": "src/main/browser/browser-route-webcontents-registry.test.ts",
"assertions": [
@@ -8013,7 +8001,7 @@
"providers": ["remote-runtime", "ssh", "wsl"],
"coveredPlatforms": ["macos", "ios", "linux"],
"coveredProviders": ["remote-runtime", "ssh", "wsl"],
"coverageNotes": "Fresh-build Playwright journeys run the same production store action against an isolated headed Electron server and a real headless orca serve host. They prove one immutable client placement owns one real retained guest on the viewing desktop, the server owns no duplicate guest, no screencast frame renders, browser.snapshot reaches the client guest, disabling the setting preserves that guest, and the next page uses the legacy server engine. Deterministic contracts cover omitted placement, missing capabilities, explicit server placement, exact renderer-store materialization after delayed publication, no fallback after client-create failure, folder workspaces, git worktrees, browserless hosts, native and WSL routes, exact connected SSH authority, reconnect command replay, lease replacement, imported-inventory cleanup, bounded retirement, and shared remote screencast fanout for multiple independent viewers. A published v1.4.184 package runs both skew directions: an old client omits placement against the current host, while a current client capability-downgrades against the old host; each creates one server guest, no client guest, and returns the exact snapshot marker. A current iOS Simulator client paired to that legacy packaged host visibly loads Example Domain through the preserved server-hosted surface. A Docker OpenSSH target proves container-only DNS and localhost through both ssh2 and system-SSH routes. Physical Windows/Linux Electron and physical mobile journeys remain gaps. The two Docker remote-only SSH browser routing journeys now run in the dedicated Linux ssh-browser-network-route CI job on full runs and their mapped source/test changes; 2 baseline and 6 repeated cases passed with no skips/retries on 2026-09-06.",
"coverageNotes": "Fresh-build Playwright journeys run the same production store action against an isolated headed Electron server and a real headless orca serve host. They prove one immutable client placement owns one real retained guest on the viewing desktop, the server owns no duplicate guest, no screencast frame renders, browser.snapshot reaches the client guest, disabling the setting preserves that guest, and the next page uses the legacy server engine. Deterministic contracts cover omitted placement, missing capabilities, explicit server placement, exact renderer-store materialization after delayed publication, no fallback after client-create failure, folder workspaces, git worktrees, browserless hosts, native and WSL routes, exact connected SSH authority, reconnect command replay, lease replacement, imported-inventory cleanup, bounded retirement, and shared remote screencast fanout for multiple independent viewers. A published v1.4.184 package runs both skew directions: an old client omits placement against the current host, while a current client capability-downgrades against the old host; each creates one server guest, no client guest, and returns the exact snapshot marker. A current iOS Simulator client paired to that legacy packaged host visibly loads Example Domain through the preserved server-hosted surface. A Docker OpenSSH target proves container-only DNS and localhost through both ssh2 and system-SSH routes. Physical Windows/Linux Electron and physical mobile journeys remain gaps. The two Docker remote-only SSH browser routing journeys now run in the dedicated Linux ssh-browser-network-route CI job on full runs and their mapped source/test changes; 2 baseline and 6 repeated cases passed with no skips/retries on 2026-09-06. Schema-only placement/navigation acceptance is excluded from behavioral and mixed-version evidence.",
"motivatingLinks": [
"https://linear.app/stably/issue/STA-4150/refactor-remote-browser-to-client-hosted-electron-webviews"
],
@@ -8022,7 +8010,7 @@
"commands": [
"pnpm exec playwright test tests/e2e/paired-client-hosted-browser.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/runtime/web-runtime-session-browser-client-placement.test.ts src/renderer/src/runtime/web-runtime-session-browser-create-failure.test.ts src/main/runtime/orca-runtime-browser-client-hosted.test.ts src/main/runtime/runtime-browser-client-page-creation.test.ts src/main/runtime/browser-host/browser-host-page-reconciliation-orchestration.test.ts src/main/runtime/browser-host/browser-host-command-ledger.test.ts",
"pnpm exec vitest run --config config/vitest.config.ts src/shared/browser-client-host-protocol.test.ts src/shared/remote-runtime-client.test.ts src/main/runtime/browser-host/browser-host-capability-selection.test.ts src/main/runtime/rpc/methods/browser-tab-create-schema.test.ts src/main/ipc/runtime-environments/runtime-environment-browser-client-host-handler.test.ts",
"pnpm exec vitest run --config config/vitest.config.ts src/shared/browser-client-host-protocol.test.ts src/shared/remote-runtime-client.test.ts src/main/runtime/browser-host/browser-host-capability-selection.test.ts src/main/ipc/runtime-environments/runtime-environment-browser-client-host-handler.test.ts",
"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/cross-version-wire/cross-version-browser-placement.unit.test.ts",
"SKIP_BUILD=1 ORCA_CROSS_VERSION_PACKAGED_EXECUTABLE=/Applications/Orca.app/Contents/MacOS/Orca pnpm exec playwright test tests/e2e/packaged-mixed-version-browser-placement.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/paired-runtime-browser-network-route.test.ts src/main/browser/browser-network-execution-route.test.ts src/main/browser/wsl-browser-network-execution-route.test.ts src/main/browser/wsl-browser-network-relay-launch.test.ts src/main/runtime/runtime-browser-network-execution-host.test.ts",
@@ -8042,7 +8030,6 @@
"src/shared/browser-client-host-protocol.test.ts",
"src/shared/remote-runtime-client.test.ts",
"src/main/runtime/browser-host/browser-host-capability-selection.test.ts",
"src/main/runtime/rpc/methods/browser-tab-create-schema.test.ts",
"src/main/ipc/runtime-environments/runtime-environment-browser-client-host-handler.test.ts",
"tests/e2e/cross-version-wire/cross-version-browser-placement.unit.test.ts",
"tests/e2e/packaged-mixed-version-browser-placement.spec.ts",
@@ -11915,7 +11902,7 @@
"providers": ["local", "daemon", "wsl"],
"coveredPlatforms": ["windows"],
"coveredProviders": ["daemon"],
"coverageNotes": "Issue #8048 now has deterministic wrapper and cold-restore re-anchor tests plus a Windows PR-CI harness that drives the built daemon through 25 real ConPTY workspace-close races while an unrelated witness PTY stays alive. A Windows-only patched-node-pty test injects EAGAIN on one ConPTY input pipe and requires only that PTY to close while an unrelated PTY remains writable; a daemon-level classifier test keeps the native exception backstop narrow. Keyboard reset, CJK repaint, WSL, and full visible Electron coverage remain gaps.",
"coverageNotes": "Issue #8048 now has deterministic wrapper and cold-restore re-anchor tests plus a Windows PR-CI harness that drives the built daemon through 25 real ConPTY workspace-close races while an unrelated witness PTY stays alive. A Windows-only patched-node-pty test injects EAGAIN on one ConPTY input pipe and requires only that PTY to close while an unrelated PTY remains writable. Keyboard reset, CJK repaint, WSL, and full visible Electron coverage remain gaps.",
"motivatingLinks": [
"https://github.com/stablyai/orca/pull/6541",
"https://github.com/stablyai/orca/pull/6858",
@@ -11929,7 +11916,7 @@
"invariant": "Windows local and daemon terminals must spawn with the intended shell, survive overlapping graceful/forced workspace teardown without affecting unrelated PTYs, contain an asynchronous ConPTY input-pipe failure to the affected terminal without killing the daemon, retain recovered scrollback across the fresh daemon's first checkpoint, accept normal Enter/Backspace/Arrow input after agent or TUI exit, render cursor/CJK/wide-glyph redraws without stale cells, and converge to nonzero applied size.",
"oracle": "The issue #8048 slice asserts one node-pty ConPTY close for a graceful-then-force sequence, atomically seeds recovered history before fresh shell output and re-anchoring, preserves recovery after seed failure plus adapter restart, and runs 25 built-daemon close races while checking victim session/PID reaping, a stable daemon PID, and a live witness PTY. The EAGAIN slice emits an error from one real patched node-pty Windows input socket, requires its terminal to become unwritable and run the normal per-PTY kill path, then writes through an unrelated PTY without an uncaught exception. A broader Windows live gate still needs shell input, resize, cursor, and CJK/wide-glyph pixel evidence.",
"commands": [
"pnpm vitest run src/main/daemon/pty-subprocess.test.ts src/main/daemon/daemon-pty-adapter.test.ts src/main/daemon/node-pty-windows-input-error.win32.test.ts src/main/daemon/daemon-native-pty-exception.test.ts",
"pnpm vitest run src/main/daemon/pty-subprocess.test.ts src/main/daemon/daemon-pty-adapter.test.ts src/main/daemon/node-pty-windows-input-error.win32.test.ts",
"pnpm build:electron-vite && node config/scripts/windows-daemon-workspace-close-repro.mjs",
"node config/scripts/windows-daemon-workspace-close-repro.mjs"
],
@@ -11937,7 +11924,6 @@
"src/main/daemon/pty-subprocess.test.ts",
"src/main/daemon/daemon-pty-adapter.test.ts",
"src/main/daemon/node-pty-windows-input-error.win32.test.ts",
"src/main/daemon/daemon-native-pty-exception.test.ts",
"config/scripts/windows-daemon-workspace-close-repro.mjs"
],
"assertionRefs": [
@@ -11960,12 +11946,6 @@
"an EAGAIN event retires only the affected patched node-pty terminal while a witness remains writable"
]
},
{
"file": "src/main/daemon/daemon-native-pty-exception.test.ts",
"assertions": [
"the daemon suppresses native PTY errno failures while rejecting non-Error and unrelated logic failures"
]
},
{
"file": "config/scripts/windows-daemon-workspace-close-repro.mjs",
"assertions": [
@@ -14732,7 +14712,7 @@
"providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"],
"coveredPlatforms": ["macos"],
"coveredProviders": [],
"coverageNotes": "Deterministic main/renderer tests run on macOS and exercise simulated Windows plus POSIX/Linux process-confirmation behavior. They cover exact local-ConPTY membership, detached-child rejection, SSH and paired-runtime host-platform routing including legacy runtime PTY IDs, active-PTY ownership after worktree host changes, Windows-to-WSL routing, unknown-metadata fallback, production handler composition, KKP authorization on every host, process-confirmed Droid routing and launch-triggered confirmation, typed-alias and forged-OSC isolation, shells without OSC 133, split/detach ownership with preserved shell classification, stale PTY exit/rebind rejection, command-generation revocation, daemon v21 warm-reattach identity, unavailable inspection, and lazy subprocess/RPC callback counts. A live linux-arm64 Docker target additionally proved real relay deployment, SSH PTY host detection, and exact inactive/active KKP bytes. The Electron byte test runs only on Windows; live Windows evidence remains uncollected. Test failures report exact expected bytes; no product telemetry or raw terminal logging is added.",
"coverageNotes": "Deterministic main/renderer tests run on macOS and exercise simulated Windows plus POSIX/Linux process-confirmation behavior. They cover exact local-ConPTY membership, detached-child rejection, SSH and paired-runtime host-platform routing including legacy runtime PTY IDs, active-PTY ownership after worktree host changes, Windows-to-WSL routing, unknown-metadata fallback, production handler composition, KKP authorization on every host, process-confirmed Droid routing and launch-triggered confirmation, typed-alias and forged-OSC isolation, shells without OSC 133, split/detach ownership with preserved shell classification, stale PTY exit/rebind rejection, command-generation revocation, daemon v21 warm-reattach identity, unavailable inspection, and lazy subprocess/RPC callback counts. A live linux-arm64 Docker target additionally proved real relay deployment, SSH PTY host detection, and exact inactive/active KKP bytes. The Electron byte test runs only on Windows; live Windows evidence remains uncollected. Test failures report exact expected bytes; no product telemetry or raw terminal logging is added. Protocol-version constant inventories are excluded from handshake and foreground-confirmation evidence.",
"motivatingLinks": [
"https://github.com/stablyai/orca/issues/7620",
"https://github.com/stablyai/orca/pull/7668"
@@ -14740,12 +14720,11 @@
"invariant": "Shift+Enter key recognition follows the client OS, while emitted bytes follow the active application and PTY host: active Kitty keyboard protocol authorizes CSI-u on every host; otherwise Windows hosts use Esc+CR except when allowlisted Droid ownership or fresh routing-trusted Droid process evidence authorizes CSI-u, and non-Windows hosts use Esc+CR. The active SSH connection, remote-runtime PTY owner, or live local session outranks later worktree ownership changes, and missing host-platform metadata falls back to the client. Every new command and PTY replacement revokes stale agent routing until current evidence settles; split or reused panes cannot inherit sibling or prior-PTY authority; unrelated keys perform no host, agent, protocol, or ConPTY lookup.",
"oracle": "Renderer tests assert exact bytes across client/PTY-host combinations, including Kitty keyboard protocol active and inactive on Windows and non-Windows hosts, and prove SSH identity, the environment encoded in an active remote-runtime PTY id, and live local-session identity outrank current worktree ownership, while unavailable platform metadata falls back to the client. A live linux-arm64 SSH PTY independently captured Esc+CR with KKP inactive and CSI-u with KKP active. Fresh Windows process evidence authorizes Droid bytes only after a recognized global candidate is intersected with the exact ConPTY console process list; detached descendants, helper failure/timeout/root-only fallback, stale PTY exit/rebind results, typed text, and hook/OSC output fail closed. A new OSC 133;C immediately publishes a routing-neutral generation, including during D-to-C races. In cmd.exe/Git Bash/custom shells without OSC 133, accepted inferred commands start the same fresh generation; accepted submit/interrupt, title exit, focus, and visibility revoke trusted Droid bytes while one bounded confirmation runs. Detach preserves the live PTY's source shell override so WSL/native classification cannot change with the current default. Ordinary fast shell commands use cached/no-scan paths; routing-relevant confirmation bypasses cached process snapshots and keeps the bounded three-read ladder. Daemon protocol v21 persists only an allowlisted launchAgent; warm reattach uses it as a display/confirmation hint and restores routing only after current process proof. The Windows Electron test focuses the real xterm textarea and records exact renderer-to-main PTY writes.",
"commands": [
"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/daemon-foreground-confirmation-protocol.test.ts src/main/daemon/daemon-pty-adapter.test.ts src/main/daemon/daemon-pty-router.test.ts src/main/daemon/daemon-server.test.ts src/main/daemon/degraded-daemon-pty-provider.test.ts src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts src/main/daemon/pty-subprocess.test.ts src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts src/main/providers/agent-foreground-process.test.ts src/main/providers/local-pty-provider-foreground-process.test.ts src/main/daemon/pty-subprocess-foreground-degraded-scan.test.ts src/main/providers/windows-console-attached-processes.test.ts src/main/providers/windows-pty-job-membership.test.ts src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.test.ts src/renderer/src/components/terminal-pane/pty-connection-foreground-agent.test.ts src/renderer/src/components/terminal-pane/pty-transport-reattach-admission.test.ts src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts src/renderer/src/store/slices/store-active-worktree-terminal-creation.test.ts src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts src/shared/agent-process-recognition.test.ts src/shared/process-table-snapshot.test.ts tests/e2e/terminal-foreground-confirmation.unit.test.ts",
"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/daemon-pty-adapter.test.ts src/main/daemon/daemon-pty-router.test.ts src/main/daemon/daemon-server.test.ts src/main/daemon/degraded-daemon-pty-provider.test.ts src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts src/main/daemon/pty-subprocess.test.ts src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts src/main/providers/agent-foreground-process.test.ts src/main/providers/local-pty-provider-foreground-process.test.ts src/main/daemon/pty-subprocess-foreground-degraded-scan.test.ts src/main/providers/windows-console-attached-processes.test.ts src/main/providers/windows-pty-job-membership.test.ts src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.test.ts src/renderer/src/components/terminal-pane/pty-connection-foreground-agent.test.ts src/renderer/src/components/terminal-pane/pty-transport-reattach-admission.test.ts src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts src/renderer/src/store/slices/store-active-worktree-terminal-creation.test.ts src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts src/shared/agent-process-recognition.test.ts src/shared/process-table-snapshot.test.ts tests/e2e/terminal-foreground-confirmation.unit.test.ts",
"pnpm run test:e2e -- tests/e2e/terminal-shortcuts.spec.ts",
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/keyboard-handlers.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-pane-handle-resolution.test.ts src/renderer/src/components/terminal-pane/terminal-input-host-platform.test.ts"
],
"testFiles": [
"src/main/daemon/daemon-foreground-confirmation-protocol.test.ts",
"src/main/daemon/daemon-pty-adapter.test.ts",
"src/main/daemon/daemon-pty-router.test.ts",
"src/main/daemon/daemon-server.test.ts",
@@ -14973,7 +14952,7 @@
"result": "passed",
"durationSeconds": 3.88,
"summary": "Twenty-six focused test files passed (489 tests) on the PR head, covering fresh-scan ordering/deduplication, exact ConPTY membership and detached-child rejection, stale PTY guards, daemon v21 launch ownership with current-process confirmation, no-OSC command/exit recovery, preserved detach shell classification, unavailable evidence, routing-neutral command generations, exact shortcut bytes, and the composed daemon-plus-tracker contract; the Windows Electron byte test remains platform-gated and is not counted as local macOS evidence.",
"currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/daemon-foreground-confirmation-protocol.test.ts src/main/daemon/daemon-pty-adapter.test.ts src/main/daemon/daemon-pty-router.test.ts src/main/daemon/daemon-server.test.ts src/main/daemon/degraded-daemon-pty-provider.test.ts src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts src/main/daemon/pty-subprocess.test.ts src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts src/main/providers/agent-foreground-process.test.ts src/main/providers/local-pty-provider-foreground-process.test.ts src/main/daemon/pty-subprocess-foreground-degraded-scan.test.ts src/main/providers/windows-console-attached-processes.test.ts src/main/providers/windows-pty-job-membership.test.ts src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.test.ts src/renderer/src/components/terminal-pane/pty-connection-foreground-agent.test.ts src/renderer/src/components/terminal-pane/pty-transport-reattach-admission.test.ts src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts src/renderer/src/store/slices/store-active-worktree-terminal-creation.test.ts src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts src/shared/agent-process-recognition.test.ts src/shared/process-table-snapshot.test.ts tests/e2e/terminal-foreground-confirmation.unit.test.ts"
"currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/daemon-pty-adapter.test.ts src/main/daemon/daemon-pty-router.test.ts src/main/daemon/daemon-server.test.ts src/main/daemon/degraded-daemon-pty-provider.test.ts src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts src/main/daemon/pty-subprocess.test.ts src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts src/main/providers/agent-foreground-process.test.ts src/main/providers/local-pty-provider-foreground-process.test.ts src/main/daemon/pty-subprocess-foreground-degraded-scan.test.ts src/main/providers/windows-console-attached-processes.test.ts src/main/providers/windows-pty-job-membership.test.ts src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.test.ts src/renderer/src/components/terminal-pane/pty-connection-foreground-agent.test.ts src/renderer/src/components/terminal-pane/pty-transport-reattach-admission.test.ts src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts src/renderer/src/store/slices/store-active-worktree-terminal-creation.test.ts src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts src/shared/agent-process-recognition.test.ts src/shared/process-table-snapshot.test.ts tests/e2e/terminal-foreground-confirmation.unit.test.ts"
}
],
"runtimeBudget": {
@@ -15026,13 +15005,13 @@
"providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"],
"coveredPlatforms": ["macos"],
"coveredProviders": ["local", "daemon"],
"coverageNotes": "Runtime and provider-contract tests on macOS cover exact-PTY authorization, verified managed-Claude launch identity, local/daemon fresh confirmation, exact ConPTY membership, and unsupported-provider fail-closed behavior. Physical Windows, live Linux, SSH, WSL, and remote-runtime validation remain explicit gaps; providers without confirmation preserve conservative refusal when no verified launch identity exists.",
"coverageNotes": "Runtime and provider-contract tests on macOS cover exact-PTY authorization, verified managed-Claude launch identity, local/daemon fresh confirmation, exact ConPTY membership, and unsupported-provider fail-closed behavior. Physical Windows, live Linux, SSH, WSL, and remote-runtime validation remain explicit gaps; providers without confirmation preserve conservative refusal when no verified launch identity exists. Protocol-version constant inventories are excluded from handshake and foreground-confirmation evidence.",
"motivatingLinks": ["https://github.com/stablyai/orca/issues/8303"],
"invariant": "A guarded note send writes only to the exact PTY binding checked by the guard and only while permission/wait evidence allows input; a generic busy title requires independent agent identity from the title, a verified managed launch bound to the current PTY incarnation, or the foreground process; fresh hook state conflicting with an ordinary shell foreground requires fresh provider confirmation of a recognized agent in that PTY.",
"oracle": "A quarter-circle Claude task title authorizes without a provider lookup only on the exact PTY incarnation carrying verified managed-Claude launch identity; the same title in a bare pane, with an unverified launch hint, or after PTY incarnation replacement is refused while current Claude activity remains a working signal. Fresh explicit state plus ordinary PowerShell plus confirmed recognized agent is sendable on the same PTY. Confirmed shell/non-agent, unavailable confirmation, PTY exit, handle rebind, or a callback PTY mismatch returns a refusal or not-writable result and writes zero bytes.",
"commands": [
"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/quarter-circle-title-send-authorization.test.ts",
"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/terminal-send.test.ts src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts src/main/providers/agent-foreground-process.test.ts src/main/providers/local-pty-provider-foreground-process.test.ts src/main/daemon/pty-subprocess-foreground-degraded-scan.test.ts src/main/providers/windows-console-attached-processes.test.ts src/main/providers/windows-pty-job-membership.test.ts src/main/daemon/daemon-foreground-confirmation-protocol.test.ts src/main/daemon/pty-subprocess.test.ts src/renderer/src/lib/active-agent-note-send-explicit-target.test.ts src/renderer/src/components/browser-pane/annotate/BrowserAnnotationSendMenuContent.test.tsx"
"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/terminal-send.test.ts src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts src/main/providers/agent-foreground-process.test.ts src/main/providers/local-pty-provider-foreground-process.test.ts src/main/daemon/pty-subprocess-foreground-degraded-scan.test.ts src/main/providers/windows-console-attached-processes.test.ts src/main/providers/windows-pty-job-membership.test.ts src/main/daemon/pty-subprocess.test.ts src/renderer/src/lib/active-agent-note-send-explicit-target.test.ts src/renderer/src/components/browser-pane/annotate/BrowserAnnotationSendMenuContent.test.tsx"
],
"testFiles": [
"src/main/runtime/quarter-circle-title-send-authorization.test.ts",
@@ -15044,7 +15023,6 @@
"src/main/daemon/pty-subprocess-foreground-degraded-scan.test.ts",
"src/main/providers/windows-console-attached-processes.test.ts",
"src/main/providers/windows-pty-job-membership.test.ts",
"src/main/daemon/daemon-foreground-confirmation-protocol.test.ts",
"src/main/daemon/pty-subprocess.test.ts",
"src/renderer/src/lib/active-agent-note-send-explicit-target.test.ts",
"src/renderer/src/components/browser-pane/annotate/BrowserAnnotationSendMenuContent.test.tsx"
@@ -15100,12 +15078,6 @@
"malformed, incomplete, timed-out, and spawn-error membership reads fail closed"
]
},
{
"file": "src/main/daemon/daemon-foreground-confirmation-protocol.test.ts",
"assertions": [
"daemons from before the fresh-confirmation RPC are rejected by protocol version"
]
},
{
"file": "src/main/daemon/pty-subprocess.test.ts",
"assertions": [
@@ -15139,7 +15111,7 @@
"runner": "local",
"platform": "macos",
"command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/terminal-send.test.ts src/main/ipc/pty-runtime-kill-and-exit.test.ts src/main/providers/agent-foreground-process.test.ts src/main/providers/local-pty-provider-foreground-process.test.ts src/main/daemon/pty-subprocess-foreground-degraded-scan.test.ts src/main/providers/windows-console-attached-processes.test.ts src/main/providers/windows-pty-job-membership.test.ts src/main/daemon/daemon-foreground-confirmation-protocol.test.ts src/main/daemon/pty-subprocess.test.ts src/renderer/src/lib/active-agent-note-send-explicit-target.test.ts src/renderer/src/components/browser-pane/annotate/BrowserAnnotationSendMenuContent.test.tsx",
"currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/terminal-send.test.ts src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts src/main/providers/agent-foreground-process.test.ts src/main/providers/local-pty-provider-foreground-process.test.ts src/main/daemon/pty-subprocess-foreground-degraded-scan.test.ts src/main/providers/windows-console-attached-processes.test.ts src/main/providers/windows-pty-job-membership.test.ts src/main/daemon/daemon-foreground-confirmation-protocol.test.ts src/main/daemon/pty-subprocess.test.ts src/renderer/src/lib/active-agent-note-send-explicit-target.test.ts src/renderer/src/components/browser-pane/annotate/BrowserAnnotationSendMenuContent.test.tsx",
"currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/terminal-send.test.ts src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts src/main/providers/agent-foreground-process.test.ts src/main/providers/local-pty-provider-foreground-process.test.ts src/main/daemon/pty-subprocess-foreground-degraded-scan.test.ts src/main/providers/windows-console-attached-processes.test.ts src/main/providers/windows-pty-job-membership.test.ts src/main/daemon/pty-subprocess.test.ts src/renderer/src/lib/active-agent-note-send-explicit-target.test.ts src/renderer/src/components/browser-pane/annotate/BrowserAnnotationSendMenuContent.test.tsx",
"result": "passed",
"durationSeconds": 13.74,
"summary": "Twelve focused test files passed (1351 tests, 1 skipped), covering runtime confirmation and PTY revalidation, guarded RPC zero-write behavior, PTY controller routing, local/daemon fresh scans, exact ConPTY membership, and unchanged renderer note routing."
@@ -21341,16 +21313,15 @@
"providers": ["local", "daemon", "ssh", "remote-runtime", "wsl"],
"coveredPlatforms": ["macos"],
"coveredProviders": ["local", "daemon"],
"coverageNotes": "Deterministic probe, adapter and rendered notice tests; the production probe also returned stalled in the affected macOS daemon. Physical Linux/Windows/WSL/SSH and remote notices remain gaps.",
"coverageNotes": "Deterministic probe, adapter and rendered notice tests; the production probe also returned stalled in the affected macOS daemon. The remaining tests do not directly cover the spawn-health precheck or diagnostic transition logging. Physical Linux/Windows/WSL/SSH and remote notices remain gaps.",
"motivatingLinks": ["docs/bug-reproductions/daemon-async-io-stall.md"],
"invariant": "An authenticated responsive daemon must not pass its full spawn health check while asynchronous I/O is stalled. Detection owns at most one unfinished probe and never infers exit, replays input or restarts processes.",
"oracle": "An uncompleted operation yields stalled while timers keep running; repeated checks add no work; completion restores healthy. The notice explains restart consequences and opens the existing review. Old and unreachable peers never yield a stalled verdict.",
"commands": [
"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/daemon/daemon-async-io-probe.test.ts src/main/daemon/daemon-async-io-spawn-health.test.ts src/main/daemon/daemon-pty-adapter-async-io-health.test.ts src/renderer/src/components/sidebar/StalledTerminalDaemonBanner.test.tsx src/main/ipc/pty/pty-management-async-io-health.test.ts --maxWorkers=2"
"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/daemon/daemon-async-io-probe.test.ts src/main/daemon/daemon-pty-adapter-async-io-health.test.ts src/renderer/src/components/sidebar/StalledTerminalDaemonBanner.test.tsx src/main/ipc/pty/pty-management-async-io-health.test.ts --maxWorkers=2"
],
"testFiles": [
"src/main/daemon/daemon-async-io-probe.test.ts",
"src/main/daemon/daemon-async-io-spawn-health.test.ts",
"src/main/daemon/daemon-pty-adapter-async-io-health.test.ts",
"src/renderer/src/components/sidebar/StalledTerminalDaemonBanner.test.tsx",
"src/main/ipc/pty/pty-management-async-io-health.test.ts"
@@ -21363,12 +21334,6 @@
"clears a stall when the original operation finally completes"
]
},
{
"file": "src/main/daemon/daemon-async-io-spawn-health.test.ts",
"assertions": [
"does not certify terminal health from a native spawn when asynchronous I/O is stalled"
]
},
{
"file": "src/renderer/src/components/sidebar/StalledTerminalDaemonBanner.test.tsx",
"assertions": [
@@ -21389,7 +21354,7 @@
"runner": "local",
"platform": "macos",
"command": "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/daemon/daemon-async-io-probe.test.ts src/main/daemon/daemon-async-io-spawn-health.test.ts src/main/daemon/daemon-pty-adapter-async-io-health.test.ts src/renderer/src/components/sidebar/StalledTerminalDaemonBanner.test.tsx src/main/ipc/pty-management-async-io-health.test.ts --maxWorkers=2",
"currentCommand": "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/daemon/daemon-async-io-probe.test.ts src/main/daemon/daemon-async-io-spawn-health.test.ts src/main/daemon/daemon-pty-adapter-async-io-health.test.ts src/renderer/src/components/sidebar/StalledTerminalDaemonBanner.test.tsx src/main/ipc/pty/pty-management-async-io-health.test.ts --maxWorkers=2",
"currentCommand": "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/daemon/daemon-async-io-probe.test.ts src/main/daemon/daemon-pty-adapter-async-io-health.test.ts src/renderer/src/components/sidebar/StalledTerminalDaemonBanner.test.tsx src/main/ipc/pty/pty-management-async-io-health.test.ts --maxWorkers=2",
"result": "passed",
"durationSeconds": 0.7,
"summary": "26 focused tests pass, including stale-incarnation rejection, contact-loss warning retention and transition-only diagnostics. Forcing healthy on timeout makes both stall tests fail. Production probe returned stalled at 5000.8 ms in the affected daemon. Isolated real-PTY fault injection reproduced blocked input and recovery. Hidden Electron CDP notice rendering, review button and recovery dismissal checked."
-1
View File
@@ -48,7 +48,6 @@ export const UNIT_EXCLUDE = [
'src/main/browser/browser-link-materialization.electron.test.ts',
'src/main/browser/browser-client-page-renderer-lifecycle.electron.test.ts',
'src/main/browser/browser-route-webrtc-egress.electron.test.ts',
'src/main/browser/browser-route-h3-egress.electron.test.ts',
'src/main/persistence/profile-state/profile-state-writer-stall.electron.test.ts',
'src/main/browser/browser-popup-compatibility.electron.test.ts',
'src/main/browser/browser-popup-adapter-compatibility.electron.test.ts',
-2
View File
@@ -7,7 +7,6 @@ export const LINUX_PACKAGE_TESTS = [
'src/main/browser/browser-link-materialization.electron.test.ts',
'src/main/browser/browser-client-page-renderer-lifecycle.electron.test.ts',
'src/main/browser/browser-route-webrtc-egress.electron.test.ts',
'src/main/browser/browser-route-h3-egress.electron.test.ts',
'src/main/persistence/profile-state/profile-state-writer-stall.electron.test.ts',
'src/main/browser/browser-popup-compatibility.electron.test.ts',
'src/main/browser/browser-popup-adapter-compatibility.electron.test.ts',
@@ -43,7 +42,6 @@ export const WINDOWS_BOUNDARY_TESTS = [
'config/scripts/electron-builder-runtime-resources.test.mjs',
'src/main/browser/browser-client-page-renderer-lifecycle.electron.test.ts',
'src/main/browser/browser-route-webrtc-egress.electron.test.ts',
'src/main/browser/browser-route-h3-egress.electron.test.ts',
'src/main/persistence/profile-state/profile-state-writer-stall.electron.test.ts',
'src/main/providers/windows-conpty-wide-char-duplication.node-pty.test.ts',
'src/main/providers/pty-repaint-wide-char-buffer.node-pty.test.ts',
@@ -1,138 +0,0 @@
export function browserRouteH3EgressElectronMain(): string {
return String.raw`
const { app, BrowserWindow, protocol, session } = require('electron')
const { readFileSync, writeFileSync } = require('node:fs')
const config = JSON.parse(readFileSync(process.argv[2], 'utf8'))
// Use a local secure scheme so secure-context gating does not mask the egress policy.
protocol.registerSchemesAsPrivileged([
{ scheme: 'probe', privileges: { standard: true, secure: true, supportFetchAPI: true } }
])
// Ignore certificate errors so TLS rejection cannot mask egress packets.
app.on('certificate-error', (event, _webContents, _url, _error, _certificate, callback) => {
event.preventDefault()
callback(true)
})
function settle(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds))
}
function webTransportScript(origin) {
return [
"(async () => {",
" let transport",
" try {",
" transport = new WebTransport('https://" + origin + "/')",
" } catch (error) { return 'construct-threw:' + String(error && error.name) }",
" try {",
" await Promise.race([",
" transport.ready,",
" new Promise((_r, reject) => setTimeout(() => reject(new Error('ProbeTimeout')), 4000))",
" ])",
" return 'ready'",
" } catch (error) {",
" return 'rejected:' + String(error && error.name)",
" } finally { try { transport.close() } catch (closeError) {} }",
"})()"
].join('\n')
}
function forcedQuicScript(origin) {
return [
"(async () => {",
" try {",
" const response = await Promise.race([",
" fetch('https://" + origin + "/', { cache: 'no-store' }),",
" new Promise((_r, reject) => setTimeout(() => reject(new Error('ProbeTimeout')), 4000))",
" ])",
" return 'fetched:' + response.status",
" } catch (error) { return 'failed:' + String(error && error.name) }",
"})()"
].join('\n')
}
const DIRECT_SOCKETS_SCRIPT =
"JSON.stringify({ tcp: typeof TCPSocket, udp: typeof UDPSocket, server: typeof TCPServerSocket })"
const DIRECT_SOCKETS_CONSTRUCT_SCRIPT =
"(() => { try { new TCPSocket('127.0.0.1', 9); return 'constructed' }" +
" catch (error) { return 'threw:' + String(error && error.name) } })()"
async function probe() {
const partition = 'persist:h3-egress-' + config.protectedSession + '-' + Date.now()
const routeSession = session.fromPartition(partition, { cache: false })
routeSession.setCertificateVerifyProc((_request, callback) => callback(0))
await routeSession.setProxy(
config.protectedSession
? {
mode: 'fixed_servers',
proxyRules: 'socks5://127.0.0.1:' + config.socksPort,
proxyBypassRules: '<-loopback>'
}
: { mode: 'direct' }
)
await routeSession.closeAllConnections()
const resolvedProxy = await routeSession.resolveProxy(
'https://' + config.host + ':' + config.forcedQuicPort + '/'
)
routeSession.protocol.handle('probe', () =>
new Response('<!doctype html><title>H3 egress probe</title>', {
headers: { 'Content-Type': 'text/html' }
})
)
const window = new BrowserWindow({
show: false,
webPreferences: { partition, sandbox: true, nodeIntegration: false, contextIsolation: true }
})
let rendererGone = 'none'
window.webContents.on('render-process-gone', (_event, details) => {
rendererGone = String(details && details.reason)
})
await window.loadURL('probe://page/')
const webTransport = await window.webContents.executeJavaScript(
webTransportScript(config.host + ':' + config.webTransportPort)
)
// Allow late datagrams to arrive before starting the next probe.
await settle(500)
const directSockets = await window.webContents.executeJavaScript(DIRECT_SOCKETS_SCRIPT)
const forcedQuic = await window.webContents.executeJavaScript(
forcedQuicScript(config.host + ':' + config.forcedQuicPort)
)
await settle(500)
// Run last because Direct Sockets kills the control renderer.
const directSocketsConstruct = await Promise.race([
window.webContents
.executeJavaScript(DIRECT_SOCKETS_CONSTRUCT_SCRIPT)
.catch((error) => 'call-failed:' + String(error && error.message)),
settle(4000).then(() => 'no-answer')
])
// Wait for asynchronous ReportBadMessage termination; the guarded arm must also finish.
for (let attempt = 0; attempt < 30 && rendererGone === 'none'; attempt += 1) {
await settle(100)
}
window.destroy()
return { resolvedProxy, webTransport, directSockets, forcedQuic, directSocketsConstruct, rendererGone }
}
async function run() {
const timeout = setTimeout(() => app.exit(2), 25000)
await app.whenReady()
const result = await probe()
writeFileSync(config.resultPath, JSON.stringify(result))
clearTimeout(timeout)
app.quit()
}
run().catch((error) => {
writeFileSync(config.resultPath, JSON.stringify({ error: String(error?.stack || error) }))
app.exit(1)
})
`
}
@@ -1,210 +0,0 @@
import { createSocket, type Socket as UdpSocket } from 'node:dgram'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { createServer, type Server, type Socket } from 'node:net'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { DISABLED_CHROMIUM_FEATURES } from '../startup/disabled-chromium-features'
import { runBrowserRouteEgressElectron } from './browser-route-egress-electron-launch'
import { browserRouteH3EgressElectronMain } from './browser-route-h3-egress-electron-main'
const PROBE_HOST = '127.0.0.1'
export type BrowserRouteH3EgressProbeResult = {
resolvedProxy: string
webTransport: string
webTransportPackets: number
directSockets: { tcp: string; udp: string; server: string }
directSocketsConstruct: string
rendererGone: string
forcedQuic: string
forcedQuicPackets: number
}
export async function runBrowserRouteH3EgressProbe(
protectedSession: boolean
): Promise<BrowserRouteH3EgressProbeResult> {
const root = mkdtempSync(join(tmpdir(), 'orca-browser-h3-egress-'))
const webTransportObserver = createSocket('udp4')
const forcedQuicObserver = createSocket('udp4')
const sockets = new Set<Socket>()
const socks = createSocksStandIn()
let result: BrowserRouteH3EgressProbeResult | null = null
let primaryFailure: unknown = null
try {
const [webTransportPort, forcedQuicPort, socksPort] = await Promise.all([
bindUdp(webTransportObserver),
bindUdp(forcedQuicObserver),
listen(socks, sockets)
])
const resultPath = join(root, 'result.json')
const mainPath = join(root, 'main.cjs')
writeFileSync(mainPath, browserRouteH3EgressElectronMain())
writeFileSync(
join(root, 'config.json'),
JSON.stringify({
forcedQuicPort,
host: PROBE_HOST,
protectedSession,
resultPath,
socksPort,
webTransportPort
})
)
const parsed = await runBrowserRouteEgressElectron(
root,
mainPath,
electronArgs(protectedSession, forcedQuicPort)
)
result = {
...readProbeFields(parsed),
webTransportPackets: countOf(webTransportObserver),
forcedQuicPackets: countOf(forcedQuicObserver)
}
} catch (error) {
primaryFailure = error
}
const cleanupFailures = await cleanup(
root,
[webTransportObserver, forcedQuicObserver],
socks,
sockets
)
if (primaryFailure || cleanupFailures.length > 0) {
throw new AggregateError(
[...(primaryFailure ? [primaryFailure] : []), ...cleanupFailures],
primaryFailure instanceof Error ? primaryFailure.message : 'browser_route_h3_probe_failed'
)
}
if (!result) {
throw new Error('browser_route_h3_probe_result_missing')
}
return result
}
const DIRECT_SOCKETS_FEATURES = [
'DirectSockets',
'DirectSocketsInSharedWorkers',
'DirectSocketsInServiceWorkers'
]
function electronArgs(protectedSession: boolean, forcedQuicPort: number): string[] {
const args = [
`--origin-to-force-quic-on=${PROBE_HOST}:${forcedQuicPort}`,
// Enable Direct Sockets in both arms so the shipped disable list must override an explicit enable.
`--enable-features=${DIRECT_SOCKETS_FEATURES.join(',')}`
]
if (protectedSession) {
args.push(`--disable-features=${DISABLED_CHROMIUM_FEATURES.join(',')}`)
}
return args
}
function readProbeFields(
parsed: Record<string, unknown>
): Omit<BrowserRouteH3EgressProbeResult, 'webTransportPackets' | 'forcedQuicPackets'> {
const { resolvedProxy, webTransport, directSockets, forcedQuic } = parsed
const { directSocketsConstruct, rendererGone } = parsed
if (
typeof resolvedProxy !== 'string' ||
typeof webTransport !== 'string' ||
typeof directSockets !== 'string' ||
typeof forcedQuic !== 'string' ||
typeof directSocketsConstruct !== 'string' ||
typeof rendererGone !== 'string'
) {
throw new Error(`browser_route_h3_probe_result_invalid:${JSON.stringify(parsed)}`)
}
return {
resolvedProxy,
webTransport,
forcedQuic,
directSocketsConstruct,
rendererGone,
directSockets: JSON.parse(directSockets) as BrowserRouteH3EgressProbeResult['directSockets']
}
}
const packetCounts = new WeakMap<UdpSocket, number>()
function countOf(socket: UdpSocket): number {
return packetCounts.get(socket) ?? 0
}
function bindUdp(socket: UdpSocket): Promise<number> {
socket.on('message', () => packetCounts.set(socket, countOf(socket) + 1))
return new Promise((resolve, reject) => {
socket.once('error', reject)
socket.bind(0, PROBE_HOST, () => {
socket.off('error', reject)
resolve(socket.address().port)
})
})
}
function createSocksStandIn(): Server {
// The probe only checks proxy selection; it does not negotiate SOCKS.
return createServer((socket) => socket.destroy())
}
function listen(server: Server, sockets: Set<Socket>): Promise<number> {
server.on('connection', (socket) => {
sockets.add(socket)
socket.on('error', () => socket.destroy())
socket.once('close', () => sockets.delete(socket))
})
return new Promise((resolve, reject) => {
server.once('error', reject)
server.listen(0, PROBE_HOST, () => {
server.off('error', reject)
const address = server.address()
if (!address || typeof address === 'string') {
reject(new Error('browser_route_h3_probe_listener_unavailable'))
return
}
resolve(address.port)
})
})
}
async function cleanup(
root: string,
observers: UdpSocket[],
socks: Server,
sockets: Set<Socket>
): Promise<unknown[]> {
const failures: unknown[] = []
for (const socket of sockets) {
socket.destroy()
}
sockets.clear()
for (const observer of observers) {
try {
await closeUdp(observer)
} catch (error) {
failures.push(error)
}
}
try {
await new Promise<void>((resolve, reject) =>
socks.close((error) => (error ? reject(error) : resolve()))
)
} catch (error) {
failures.push(error)
}
try {
rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })
} catch (error) {
failures.push(error)
}
return failures
}
function closeUdp(socket: UdpSocket): Promise<void> {
return new Promise((resolve) => {
try {
socket.close(() => resolve())
} catch {
resolve()
}
})
}
@@ -1,32 +0,0 @@
import { describe, expect, it } from 'vitest'
import { runBrowserRouteH3EgressProbe } from './browser-route-h3-egress-fixture'
describe('browser route HTTP/3 and Direct Sockets egress under Electron', () => {
it('keeps every UDP egress path off the desktop and hides the renderer-killing constructors', async () => {
const baseline = await runBrowserRouteH3EgressProbe(false)
const guarded = await runBrowserRouteH3EgressProbe(true)
expect(baseline.resolvedProxy).toBe('DIRECT')
expect(guarded.resolvedProxy).toMatch(/^SOCKS5 127\.0\.0\.1:\d+$/)
expect(baseline.webTransportPackets).toBeGreaterThan(0)
expect(guarded.webTransport).toMatch(/^rejected:/)
expect(guarded.webTransportPackets).toBe(0)
expect(baseline.forcedQuicPackets).toBeGreaterThan(0)
expect(guarded.forcedQuicPackets).toBe(0)
expect(baseline.directSockets).toEqual({ tcp: 'function', udp: 'function', server: 'function' })
// ReportBadMessage may arrive after the constructor returns; renderer death is the signal.
expect(baseline.directSocketsConstruct).not.toMatch(/^threw:ReferenceError/)
// The same termination is reported as killed or crashed across platforms.
expect(['killed', 'crashed']).toContain(baseline.rendererGone)
expect(guarded.directSockets).toEqual({
tcp: 'undefined',
udp: 'undefined',
server: 'undefined'
})
expect(guarded.directSocketsConstruct).toBe('threw:ReferenceError')
expect(guarded.rendererGone).toBe('none')
}, 90_000)
})
@@ -1,42 +0,0 @@
import { expect, it } from 'vitest'
import { planImportWrites } from './browser-cookie-import-write'
import { summarizePartitionSkips } from './browser-cookie-partition-summary'
const readable = { status: 'unpartitioned' } as const
const unreadable = { status: 'unreadable', reason: 'synthetic incomplete partition' } as const
it('omits skip metadata when every cookie can be written', () => {
expect(
summarizePartitionSkips(
planImportWrites([{ domain: 'example.com', partition: readable }]).skips
)
).toEqual({})
})
it.each([false, true])(
'counts unreadable and withheld cookies independently (reverse: %s)',
(reverse) => {
const cookies = [
{ domain: 'example.com', partition: readable },
{ domain: 'sub.example.com', partition: unreadable },
{ domain: 'other.example.net', partition: readable }
]
const plan = planImportWrites(reverse ? cookies.toReversed() : cookies)
expect(plan.writes).toHaveLength(1)
expect(summarizePartitionSkips(plan.skips)).toEqual({
partitionSkippedCookies: 2,
partitionSkipBreakdown: { unreadableCookies: 1, preservedRelatedCookies: 1 }
})
}
)
it('does not count two unreadable cookies as related readable skips', () => {
const plan = planImportWrites([
{ domain: 'example.com', partition: unreadable },
{ domain: 'sub.example.com', partition: unreadable }
])
expect(summarizePartitionSkips(plan.skips)).toEqual({
partitionSkippedCookies: 2,
partitionSkipBreakdown: { unreadableCookies: 2, preservedRelatedCookies: 0 }
})
})
@@ -4,21 +4,6 @@ import { buildCodexAppServerExitError } from './codex-app-server-exit-error'
import { PROVIDER_SPAWN_FAILURE_MARKER } from '../../provider-process/provider-spawn-failure-report'
describe('buildCodexAppServerExitError', () => {
it("keeps the stderr tail apart from Orca's wording, as log text", () => {
const error = buildCodexAppServerExitError(' thread panicked at main.rs:4 ')
expect(error.message).toBe('codex app-server connection ended: thread panicked at main.rs:4')
expect(providerDiagnosticOf(error)).toEqual({
text: 'thread panicked at main.rs:4',
audience: 'log'
})
})
it('carries no diagnostic when a cause, not the stderr, explains the end', () => {
const error = buildCodexAppServerExitError('ignored', new Error('spawn codex ENOENT'))
expect(providerDiagnosticOf(error)).toBeUndefined()
expect(providerDiagnosticOf(buildCodexAppServerExitError(''))).toBeUndefined()
})
it('shows a supervisor spawn failure as the spawn error a direct spawn gives', () => {
const report = JSON.stringify({
thrown: false,
@@ -5,15 +5,6 @@ const START = '# BEGIN ORCA AGENT STATUS HOOKS'
const END = '# END ORCA AGENT STATUS HOOKS'
describe('legacy Codex managed profile block', () => {
it('strips a well-formed block and keeps the surrounding config', () => {
const content = `model = "o3"\n\n${START}\n[[hooks]]\nx = 1\n${END}\n\ntail = true\n`
expect(stripLegacyManagedProfileBlock(content)).toBe('model = "o3"\n\ntail = true\n')
})
it('leaves a file with no managed block untouched', () => {
expect(stripLegacyManagedProfileBlock('model = "o3"\n')).toBe('model = "o3"\n')
})
it('rejoins a CRLF config with CRLF', () => {
const content = `model = "o3"\r\n\r\n${START}\r\n[[hooks]]\r\n${END}\r\n\r\ntail = true\r\n`
const next = stripLegacyManagedProfileBlock(content)
@@ -1,37 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { grantMock } = vi.hoisted(() => ({ grantMock: vi.fn() }))
vi.mock('./codex-windows-sandbox-read-grant', () => ({
grantCodexSandboxReadOnManagedHome: grantMock
}))
vi.mock('./hook-service', () => ({
codexHookService: { prepareRuntimeHomeForLaunch: vi.fn(async () => ({ state: 'ok' })) }
}))
vi.mock('../wsl', () => ({ getDefaultWslDistro: () => 'Ubuntu' }))
vi.mock('./codex-hook-reconcile', () => ({ reconcileCodexHooksForLaunch: vi.fn() }))
import type { CodexRuntimeHomeService } from '../codex-accounts/runtime-home-service'
import { createCodexRuntimeHomeLaunchPreparation } from './codex-runtime-home-launch-preparation'
function prepareWithHome(homePath: string) {
const runtimeHome: Pick<CodexRuntimeHomeService, 'prepareForCodexLaunchAsync'> = {
prepareForCodexLaunchAsync: async () => homePath
}
return createCodexRuntimeHomeLaunchPreparation({
getRuntimeHome: () => runtimeHome,
getSettings: () => undefined
})
}
beforeEach(() => {
grantMock.mockReset()
})
describe('Codex launch preparation sandbox read grant', () => {
it('grants on host managed homes but not on WSL homes', async () => {
await prepareWithHome('C:\\orca\\codex-runtime-home\\home')({ runtime: 'host' })
await prepareWithHome('/home/me/.codex')({ runtime: 'wsl', wslDistro: 'Ubuntu' })
expect(grantMock.mock.calls).toEqual([['C:\\orca\\codex-runtime-home\\home']])
})
})
@@ -1,45 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
isComputerSidecarDiagnostic,
reportComputerDiagnostic
} from './computer-sidecar-diagnostics'
describe('computer sidecar diagnostics', () => {
const originalSend = process.send
afterEach(() => {
process.send = originalSend
vi.restoreAllMocks()
})
it('sends over IPC when running inside the sidecar', () => {
const send = vi.fn((_message: unknown) => true)
process.send = send as unknown as typeof process.send
const console_ = vi.spyOn(console, 'warn').mockImplementation(() => {})
reportComputerDiagnostic('fell back to Bypass')
// The sidecar's stdout is piped and never read, so this must not go there.
expect(console_).not.toHaveBeenCalled()
expect(send).toHaveBeenCalledWith({
kind: 'computer-sidecar-diagnostic',
message: 'fell back to Bypass'
})
expect(isComputerSidecarDiagnostic(send.mock.calls[0][0])).toBe(true)
})
it('logs directly when there is no IPC channel', () => {
process.send = undefined
const console_ = vi.spyOn(console, 'warn').mockImplementation(() => {})
reportComputerDiagnostic('fell back to Bypass')
expect(console_).toHaveBeenCalledWith('[computer-use] fell back to Bypass')
})
it('does not mistake a sidecar response for a diagnostic', () => {
expect(isComputerSidecarDiagnostic({ id: 1, ok: true, result: {} })).toBe(false)
expect(isComputerSidecarDiagnostic({ kind: 'computer-sidecar-diagnostic' })).toBe(false)
expect(isComputerSidecarDiagnostic(null)).toBe(false)
})
})
@@ -1,35 +0,0 @@
import { describe, expect, it } from 'vitest'
import { mapBridgeError } from './desktop-script-provider-bridge'
describe('mapBridgeError', () => {
it('maps native window-not-found messages without broad false positives', () => {
expect(mapBridgeError('No top-level AT-SPI window is available for Text Editor').code).toBe(
'window_not_found'
)
expect(mapBridgeError("app 'Finder' has no on-screen window").code).toBe('window_not_found')
expect(mapBridgeError('Failed to execute window operation').code).toBe('accessibility_error')
})
it('maps native element-not-found messages without broad false positives', () => {
expect(
mapBridgeError('stale element frame; run get-app-state again and use a fresh element index')
.code
).toBe('element_not_found')
expect(mapBridgeError('unknown element_index').code).toBe('element_not_found')
expect(mapBridgeError('element metadata unavailable').code).toBe('accessibility_error')
})
it('names the python3 that could not load PyGObject', () => {
const error = mapBridgeError(
"PyGObject unavailable in interpreter: /home/me/.pyenv/shims/python3\nNo module named 'gi'"
)
expect(error.code).toBe('unsupported_capability')
expect(error.message).toContain('(/home/me/.pyenv/shims/python3)')
})
it('says computer use is unavailable when no python3 is on PATH', () => {
const error = mapBridgeError('spawn python3 ENOENT')
expect(error.code).toBe('unsupported_capability')
expect(error.message).toContain("Computer use isn't available on this host")
})
})
@@ -1,48 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS } from '../../shared/clipboard-text'
import {
createDesktopScriptProviderClient,
expectDesktopProviderSubprocessStartCount,
mockBridgeResponse,
resetDesktopScriptProviderTestHarness,
sampleBridgeSnapshot,
sampleCapabilities
} from './desktop-script-provider-test-harness'
describe('DesktopScriptProviderClient paste validation', () => {
afterEach(resetDesktopScriptProviderTestHarness)
it('yields while validating large accepted pasteText payloads before launching the provider', async () => {
vi.useFakeTimers()
mockBridgeResponse({
ok: true,
capabilities: sampleCapabilities()
})
mockBridgeResponse({
ok: true,
action: {
path: 'clipboard',
actionName: 'paste',
fallbackReason: null
},
snapshot: sampleBridgeSnapshot('Text Editor', 'pasted')
})
const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py')
const text = 'é'.repeat(CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS + 1)
const call = client.action('pasteText', {
app: 'Text Editor',
text,
noScreenshot: true
})
await Promise.resolve()
expectDesktopProviderSubprocessStartCount(0)
await vi.advanceTimersByTimeAsync(0)
await expect(call).resolves.toMatchObject({
action: { path: 'clipboard' }
})
expectDesktopProviderSubprocessStartCount(2)
})
})
@@ -1,41 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { showMessageBoxMock } = vi.hoisted(() => ({
showMessageBoxMock: vi.fn()
}))
vi.mock('electron', () => ({
dialog: { showMessageBox: showMessageBoxMock }
}))
import { promptForGpuFallbackRestart } from './gpu-fallback-restart-prompt'
beforeEach(() => {
showMessageBoxMock.mockReset()
})
describe('promptForGpuFallbackRestart', () => {
it('offers a restart without forcing it', async () => {
const parentWindow = { id: 1 }
showMessageBoxMock.mockResolvedValue({ response: 0 })
await expect(promptForGpuFallbackRestart(parentWindow as never)).resolves.toBe('restart')
expect(showMessageBoxMock).toHaveBeenCalledWith(parentWindow, {
type: 'warning',
buttons: ['Restart in Safe Graphics Mode', 'Keep Running'],
defaultId: 0,
cancelId: 1,
title: 'Restart Orca in Safe Graphics Mode?',
message: "Orca's graphics process has crashed repeatedly.",
detail:
'Safe graphics mode disables hardware acceleration and WebGL for this Orca version. Terminals and 3D content may render more slowly. Keep Running leaves graphics settings unchanged.'
})
})
it('treats the secondary or dismissed response as continue', async () => {
showMessageBoxMock.mockResolvedValue({ response: 1 })
await expect(promptForGpuFallbackRestart()).resolves.toBe('continue')
expect(showMessageBoxMock).toHaveBeenCalledOnce()
})
})
@@ -1,51 +0,0 @@
import { describe, expect, it } from 'vitest'
import { buildSuppressedProcessGoneBreadcrumbData } from './suppressed-process-gone-breadcrumb'
describe('buildSuppressedProcessGoneBreadcrumbData', () => {
it('preserves child process identity on suppressed breadcrumbs', () => {
expect(
buildSuppressedProcessGoneBreadcrumbData({
source: 'child',
processType: 'Utility',
reason: 'killed',
exitCode: 1,
expectedTeardown: 'app-shutdown',
details: {
name: 'Network Service',
serviceName: 'network.mojom.NetworkService',
// Distinct from processType: proves type comes from details.type.
type: 'GPU',
nested: { ignored: true }
}
})
).toEqual({
source: 'child',
processType: 'Utility',
reason: 'killed',
exitCode: 1,
expectedTeardown: 'app-shutdown',
name: 'Network Service',
serviceName: 'network.mojom.NetworkService',
type: 'GPU'
})
})
it('drops empty and non-string identity fields', () => {
expect(
buildSuppressedProcessGoneBreadcrumbData({
source: 'renderer',
processType: 'renderer',
reason: 'crashed',
exitCode: null,
expectedTeardown: 'none',
details: { name: '', serviceName: 42, type: undefined }
})
).toEqual({
source: 'renderer',
processType: 'renderer',
reason: 'crashed',
exitCode: null,
expectedTeardown: 'none'
})
})
})
@@ -1,34 +0,0 @@
import { afterEach, expect, it, vi } from 'vitest'
const { health, spawn } = vi.hoisted(() => ({ health: vi.fn(), spawn: vi.fn() }))
vi.mock('./daemon-async-io-probe', () => ({ checkDaemonAsyncIo: health }))
vi.mock('node-pty', () => ({ spawn }))
import { runPtySpawnHealthProbe } from './pty-subprocess/spawn-preflight'
import { DaemonHealthRequests } from './daemon-health-requests'
afterEach(() => vi.clearAllMocks())
it('does not certify terminal health from a native spawn when asynchronous I/O is stalled', async () => {
health.mockResolvedValue({ state: 'stalled', pendingMs: 5000 })
await expect(runPtySpawnHealthProbe()).rejects.toThrow('asynchronous I/O is stalled')
expect(spawn).not.toHaveBeenCalled()
})
it('reports asynchronous progress and logs only transitions into and out of a stall', async () => {
const log = vi.fn()
const handler = new DaemonHealthRequests(vi.fn(), { log })
const request = { id: 'health', type: 'asyncIoHealth' } as const
health.mockResolvedValue({ state: 'healthy', pendingMs: 0 })
expect(await handler.handle(request)).toEqual({ state: 'healthy', pendingMs: 0 })
expect(log).not.toHaveBeenCalled()
health.mockResolvedValue({ state: 'stalled', pendingMs: 5000 })
expect(await handler.handle(request)).toEqual({ state: 'stalled', pendingMs: 5000 })
await handler.handle(request)
health.mockResolvedValue({ state: 'healthy', pendingMs: 0 })
await handler.handle(request)
expect(log.mock.calls).toEqual([
['async-io-stalled', { pendingMs: 5000 }],
['async-io-recovered', { pendingMs: 0 }]
])
})
@@ -1,28 +0,0 @@
import { describe, expect, it } from 'vitest'
import { PREVIOUS_DAEMON_PROTOCOL_VERSIONS, PROTOCOL_VERSION } from './types'
describe('foreground-confirmation daemon protocol', () => {
it('rejects daemons from before the fresh-confirmation RPC', () => {
expect(PROTOCOL_VERSION).toBe(52)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(19)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(22)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(23)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(24)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(25)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(26)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(27)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(28)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(29)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(30)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(31)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(32)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(33)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(34)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(35)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(36)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(37)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(38)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(39)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(51)
})
})
@@ -1,37 +0,0 @@
import { describe, expect, it } from 'vitest'
import { isNativePtyException } from './daemon-native-pty-exception'
describe('isNativePtyException', () => {
it.each([
Object.assign(new Error('write EAGAIN'), {
code: 'EAGAIN',
stack: 'Error: write EAGAIN\n at node-pty/lib/windowsTerminal.js:1:1'
}),
Object.assign(new Error('read EIO'), {
stack: 'Error: read EIO\n at /app/node_modules/node-pty/lib/unixTerminal.js:1:1'
}),
new Error('Pty process exited'),
new Error('Invalid pty handle'),
new Error('ioctl(2) failed, EBADF'),
Object.assign(new Error('native write failed'), {
code: 'EPIPE',
stack: 'Error: native write failed\n at node-pty/lib/windowsTerminal.js:1:1'
})
])('contains native PTY failures without killing the daemon', (error) => {
expect(isNativePtyException(error)).toBe(true)
})
it.each([
new Error('database invariant failed'),
new Error('database write EAGAIN'),
new Error('write EPIPE'),
new Error('pty metadata invariant failed'),
new Error('node-pty metadata invariant failed'),
Object.assign(new Error('database write failed'), { code: 'EAGAIN' }),
Object.assign(new Error('socket write failed'), { code: 'EPIPE' }),
new TypeError('logic bug'),
'EAGAIN'
])('does not suppress unrelated or malformed failures', (error) => {
expect(isNativePtyException(error)).toBe(false)
})
})
@@ -1,31 +0,0 @@
import { afterEach, describe, expect, it } from 'vitest'
import { resolveFallbackForegroundProcess } from './foreground-fallback-process'
import { setTerminalScopesForTest } from '../terminal-scopes-runtime'
describe('resolveFallbackForegroundProcess', () => {
afterEach(() => setTerminalScopesForTest(null))
// Terminal scopes are Linux-only; Windows also substitutes the shell for an empty name.
it.skipIf(process.platform === 'win32')(
'reads the terminal scope wrappers as the shell, but a user-typed systemd-run as work',
() => {
setTerminalScopesForTest({
slice: 'orca_ptys_a.slice',
sliceCgroupPath: '/sys/fs/cgroup/x/orca_ptys_a.slice',
systemdRun: '/usr/bin/systemd-run',
envBinary: '/usr/bin/env',
launchId: 'a',
properties: []
})
expect(resolveFallbackForegroundProcess('/usr/bin/systemd-run', '/bin/bash')).toBe('bash')
expect(resolveFallbackForegroundProcess('/usr/bin/env', '/bin/bash')).toBe('bash')
expect(resolveFallbackForegroundProcess('/usr/bin/systemd-run', '/usr/bin/zsh')).toBe('zsh')
expect(resolveFallbackForegroundProcess('systemd-run', '/bin/bash')).toBe('systemd-run')
expect(resolveFallbackForegroundProcess('/usr/bin/bash', '/bin/bash')).toBe('bash')
}
)
it('keeps every name while terminal scopes are off', () => {
expect(resolveFallbackForegroundProcess('/usr/bin/systemd-run', '/bin/zsh')).toBe('systemd-run')
})
})
@@ -1,47 +0,0 @@
import { describe, expect, it } from 'vitest'
import { compareBufferRows } from './serialize-grid-cell-descriptors'
import { createFuzzTerminal, writeTerminal } from './serialize-grid-roundtrip'
describe('serialize grid comparison policy', () => {
it.each([
['abc界', 'abc ', 4, false],
['abc界', 'abc\x1b[48;2;1;2;3m ', 4, false],
['abc ', 'abc界', 4, true],
['é', 'è', 8, true],
['\x1b[32mA', '\x1b[38;5;2mA', 8, false],
['\x1b[42m ', '\x1b[48;5;2m ', 8, false],
['\x1b[7;31m ', '\x1b[7;32m ', 8, true],
['\x1b[4m\x1b[2J', '\x1b[2J', 8, false],
['\x1b[4m ', ' ', 8, true],
['\x1b[4m \x1b[0mB', ' B', 8, true],
['text\r\n', 'text', 8, false],
['text\r\n\x1b[48;2;1;2;3m\x1b[2K', 'text', 8, true]
] as const)(
'preserves blank, clipped and color policy for %j / %j',
(expected, actual, cols, differs) => {
const source = createFuzzTerminal({ cols: 8, rows: 4, scrollback: 10 })
const replay = createFuzzTerminal({ cols: 8, rows: 4, scrollback: 10 })
try {
writeTerminal(source, expected)
writeTerminal(replay, actual)
expect(
Boolean(
compareBufferRows(
'policy',
source.buffer.active,
0,
source.buffer.active.length,
replay.buffer.active,
0,
replay.buffer.active.length,
cols
)
)
).toBe(differs)
} finally {
source.dispose()
replay.dispose()
}
}
)
})
@@ -1,18 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it } from 'vitest'
import { waitForTerminalAttachOperation } from './terminal-attach-cancellation'
describe('terminal attach cancellation', () => {
it('removes cancellation listeners when the operation settles first', async () => {
const controller = new AbortController()
const removeListener = vi.spyOn(controller.signal, 'removeEventListener')
await expect(
waitForTerminalAttachOperation(Promise.resolve('ready'), controller.signal, 'session-1')
).resolves.toBe('ready')
expect(removeListener).toHaveBeenCalledTimes(1)
})
it('preserves operation-first ordering when settlement and abort share a turn', async () => {
const controller = new AbortController()
const operation = Promise.withResolvers<string>()
@@ -25,14 +14,4 @@ describe('terminal attach cancellation', () => {
controller.abort()
await expect(waiting).resolves.toBe('ready')
})
it('rejects promptly on cancellation while the operation remains pending', async () => {
const controller = new AbortController()
const operation = new Promise<void>(() => {})
const waiting = waitForTerminalAttachOperation(operation, controller.signal, 'session-2')
controller.abort()
await expect(waiting).rejects.toMatchObject({ name: 'TerminalAttachCanceledError' })
})
})
@@ -28,13 +28,4 @@ describe('normalizeWslColdRestoreCwd', () => {
])('falls back instead of guessing for %s', (recoveredCwd) => {
expect(normalizeWslColdRestoreCwd({ ...base, recoveredCwd })).toBe(base.requestedCwd)
})
it('leaves native and missing-context restores unchanged', () => {
expect(
normalizeWslColdRestoreCwd({ ...base, platform: 'linux', recoveredCwd: '/home/jin' })
).toBe('/home/jin')
expect(
normalizeWslColdRestoreCwd({ ...base, wslDistro: undefined, recoveredCwd: '\\\\server\\x' })
).toBe('\\\\server\\x')
})
})
@@ -1,38 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { AndroidCommandResult, AndroidCommandRunner } from './android-command-runner'
import type { AndroidSdkPaths } from './android-sdk-discovery'
import { androidExec, androidTap } from './android-input-commands'
const SDK: AndroidSdkPaths = {
sdkRoot: '/sdk',
adb: '/sdk/adb',
emulator: '/sdk/emulator',
avdmanager: '/sdk/avdmanager'
}
const ok: AndroidCommandResult = { stdout: 'ok', stderr: '', code: 0 }
const fail: AndroidCommandResult = { stdout: '', stderr: 'device offline', code: 1 }
describe('android input commands', () => {
it('throws when adb tap exits non-zero', async () => {
const runner: AndroidCommandRunner = async () => fail
await expect(
androidTap(runner, SDK, 'emulator-5554', 0.5, 0.5, { width: 100, height: 200 })
).rejects.toMatchObject({
code: 'emulator_error',
message: 'adb tap failed: device offline'
})
})
it('returns stdout for successful exec and throws for failed exec', async () => {
const successRunner: AndroidCommandRunner = async () => ok
await expect(androidExec(successRunner, SDK, 'emulator-5554', 'echo ok')).resolves.toBe('ok')
const failRunner: AndroidCommandRunner = async () => fail
await expect(androidExec(failRunner, SDK, 'emulator-5554', 'false')).rejects.toMatchObject({
code: 'emulator_error',
message: 'adb exec failed: device offline'
})
})
})
@@ -1,53 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
SCRCPY_DEVICE_JAR_PATH,
SCRCPY_SERVER_VERSION,
pushScrcpyServerArgs,
scrcpyForwardArgs,
scrcpyRemoveForwardArgs,
startScrcpyServerArgs
} from './scrcpy-server-deploy'
describe('scrcpy deploy args', () => {
it('builds the push, forward, and remove-forward commands', () => {
expect(pushScrcpyServerArgs('emulator-5554', '/local/scrcpy-server')).toEqual([
'-s',
'emulator-5554',
'push',
'/local/scrcpy-server',
SCRCPY_DEVICE_JAR_PATH
])
expect(scrcpyForwardArgs('emulator-5554', 27183, 'abcd1234')).toEqual([
'-s',
'emulator-5554',
'forward',
'tcp:27183',
'localabstract:scrcpy_abcd1234'
])
expect(scrcpyRemoveForwardArgs('emulator-5554', 27183)).toEqual([
'-s',
'emulator-5554',
'forward',
'--remove',
'tcp:27183'
])
})
it('starts the server with the pinned version and h264 options', () => {
const args = startScrcpyServerArgs('emulator-5554', { scid: 'abcd1234', maxSize: 1024 })
expect(args.slice(0, 8)).toEqual([
'-s',
'emulator-5554',
'shell',
`CLASSPATH=${SCRCPY_DEVICE_JAR_PATH}`,
'app_process',
'/',
'com.genymobile.scrcpy.Server',
SCRCPY_SERVER_VERSION
])
expect(args).toContain('scid=abcd1234')
expect(args).toContain('video_codec=h264')
expect(args).toContain('control=true')
expect(args).toContain('max_size=1024')
})
})
-37
View File
@@ -1,37 +0,0 @@
import { describe, expect, it } from 'vitest'
import { isPlausibleHostedLogin } from './git-username'
describe('isPlausibleHostedLogin', () => {
it('accepts ordinary GitHub logins', () => {
expect(isPlausibleHostedLogin('octocat')).toBe(true)
expect(isPlausibleHostedLogin('mona-lisa')).toBe(true)
expect(isPlausibleHostedLogin('a')).toBe(true)
expect(isPlausibleHostedLogin('a'.repeat(39))).toBe(true)
})
it('accepts Enterprise Managed User logins, which carry a _shortcode suffix', () => {
expect(isPlausibleHostedLogin('octocat_acme')).toBe(true)
expect(isPlausibleHostedLogin('mona-lisa_acme')).toBe(true)
expect(isPlausibleHostedLogin(`${'a'.repeat(34)}_acme`)).toBe(true)
})
it('still rejects leading or trailing separators, double hyphens and non-tokens', () => {
expect(isPlausibleHostedLogin('_acme')).toBe(false)
expect(isPlausibleHostedLogin('octocat_')).toBe(false)
expect(isPlausibleHostedLogin('-octocat')).toBe(false)
expect(isPlausibleHostedLogin('octocat-')).toBe(false)
expect(isPlausibleHostedLogin('octo--cat')).toBe(false)
expect(isPlausibleHostedLogin('{"message":"API rate limit exceeded"}')).toBe(false)
expect(isPlausibleHostedLogin('a'.repeat(40))).toBe(false)
for (const login of [
'octocat_acme/branch',
'octocat_acme\\branch',
'octocat_acme\nother',
'octocat_acme.lock',
'octocat_acme other'
]) {
expect(isPlausibleHostedLogin(login)).toBe(false)
}
})
})
@@ -20,10 +20,6 @@ describe('getPRReviewCommentLineNumbersFromPatch', () => {
expect(getPRReviewCommentLineNumbersFromPatch(patch)).toEqual([20, 21, 22, 23, 51, 52])
})
it('returns an empty list when GitHub omits the patch', () => {
expect(getPRReviewCommentLineNumbersFromPatch(undefined)).toEqual([])
})
it('counts added lines whose content begins with ++', () => {
// Inside a hunk +++count is added ++count content, not a file header.
const patch = ['@@ -1,1 +1,2 @@', ' const a = 1', '+++count'].join('\n')
@@ -3,7 +3,6 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { getHermesHome } from './hermes-default-home'
import { HermesHookService } from './hook-service'
const realPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
@@ -16,12 +15,6 @@ describe('Hermes home on Windows', () => {
}
})
it('keeps an explicit HERMES_HOME ahead of the LOCALAPPDATA default', () => {
expect(getHermesHome({ HERMES_HOME: 'D:\\profiles\\hermes', LOCALAPPDATA: tmpdir() })).toBe(
'D:\\profiles\\hermes'
)
})
it('installs and reports hook status under %LOCALAPPDATA%\\hermes (#24966)', () => {
const root = mkdtempSync(join(tmpdir(), 'orca-hermes-win-'))
try {
@@ -1,41 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { createFromBuffer } = vi.hoisted(() => ({ createFromBuffer: vi.fn() }))
vi.mock('electron', () => ({ nativeImage: { createFromBuffer } }))
import { encodeRepoIconPng } from './electron-repo-icon-png'
function fakeImage(width: number, height: number, png = Buffer.from([1])) {
const image = {
isEmpty: () => width === 0,
getSize: () => ({ width, height }),
resize: vi.fn((size: { width: number; height: number }) => fakeImage(size.width, size.height)),
toPNG: () => png
}
return image
}
describe('encodeRepoIconPng', () => {
beforeEach(() => createFromBuffer.mockReset())
it('scales the long edge down to the limit, keeping the aspect ratio', () => {
const image = fakeImage(400, 200)
createFromBuffer.mockReturnValue(image)
expect(encodeRepoIconPng(new Uint8Array([9]), 64)).toEqual(Buffer.from([1]))
expect(image.resize).toHaveBeenCalledWith({ width: 64, height: 32, quality: 'best' })
})
it('never upscales a small icon', () => {
const image = fakeImage(16, 16)
createFromBuffer.mockReturnValue(image)
encodeRepoIconPng(new Uint8Array([9]), 64)
expect(image.resize).not.toHaveBeenCalled()
})
it('answers null for bytes the decoder cannot read', () => {
createFromBuffer.mockReturnValue(fakeImage(0, 0))
expect(encodeRepoIconPng(new Uint8Array([9]), 64)).toBeNull()
})
})
@@ -1,36 +0,0 @@
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
const created = vi.hoisted((): string[] => [])
vi.mock('../shared/secure-path-windows-acl', () => ({
writeRestrictedWindowsFile: (path: string, contents: string | Buffer) => {
created.push(path)
writeFileSync(path, contents)
return true
}
}))
describe('writeCredentialFileAtomic on Windows', () => {
const platform = process.platform
afterEach(() => {
Object.defineProperty(process, 'platform', { value: platform })
})
it('stages the replacement as a born-restricted file, so the owner-only ACL survives', async () => {
const { writeCredentialFileAtomic } = await import('./integration-credential-file')
const dir = mkdtempSync(join(tmpdir(), 'credential-acl-'))
try {
Object.defineProperty(process, 'platform', { value: 'win32' })
const target = join(dir, 'linear-token.enc')
expect(writeCredentialFileAtomic(target, Buffer.from([0, 1, 2, 3]))).toBe(true)
expect(created).toHaveLength(1)
expect(created[0]).toMatch(/linear-token\.enc\..+\.tmp$/)
expect(readFileSync(target)).toEqual(Buffer.from([0, 1, 2, 3]))
} finally {
Object.defineProperty(process, 'platform', { value: platform })
rmSync(dir, { recursive: true, force: true })
}
})
})
@@ -1,24 +1,5 @@
import { expect, it } from 'vitest'
import { decodeMergedSearchCursor, encodeMergedSearchCursor } from './ai-vault-search-merged-cursor'
const cursor = {
limit: 20,
sort: 'newest',
hosts: {
local: { c: null, e: 3, g: 7 },
'ssh:box': { c: 'opaque', e: 0, g: 2 }
}
} as const
it('round-trips a merged cursor through base64url', () => {
expect(decodeMergedSearchCursor(encodeMergedSearchCursor(cursor))).toEqual(cursor)
})
it('refuses anything that is not a cursor this module minted', () => {
for (const raw of ['', 'not-base64url!!', Buffer.from('{]').toString('base64url')]) {
expect(decodeMergedSearchCursor(raw)).toBeNull()
}
})
import { decodeMergedSearchCursor } from './ai-vault-search-merged-cursor'
it('refuses a payload whose shape would change what a skip count means', () => {
const refused = [
+1 -12
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { DEFAULT_WARNING_DEDUPE_MAX_KEYS, shouldEmitBoundedWarning } from './bounded-warning-dedupe'
import { shouldEmitBoundedWarning } from './bounded-warning-dedupe'
describe('shouldEmitBoundedWarning', () => {
it('keeps retained warning keys quiet without cascade eviction after saturation', () => {
@@ -17,15 +17,4 @@ describe('shouldEmitBoundedWarning', () => {
expect([...warningKeys]).toEqual(['retained-1', 'retained-2', 'retained-3'])
})
it('limits repeat emissions for a stable default-cap-plus-one scan', () => {
const warningKeys = new Set<string>()
const keys = Array.from(
{ length: DEFAULT_WARNING_DEDUPE_MAX_KEYS + 1 },
(_, index) => `warning-${index}`
)
expect(keys.filter((key) => shouldEmitBoundedWarning(warningKeys, key))).toEqual(keys)
expect(keys.filter((key) => shouldEmitBoundedWarning(warningKeys, key))).toEqual([keys.at(-1)])
})
})
@@ -32,10 +32,6 @@ it('reads only the requested bytes and reports partial and past-EOF ranges', asy
})
})
it('refuses directories through the shared regular-file guard', async () => {
await expect(readLocalFileRange(folder, 0, 4)).rejects.toThrow()
})
it('rejects invalid or excessive ranges before opening the path', async () => {
for (const [offset, length] of [
[-1, 1],
@@ -1,37 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { OrcaRuntimeService } from '../../../runtime/orca-runtime'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch'
import { pendingByPaneKey } from './serializer-state'
import { seedHeadlessTerminalFromSpawnResult } from './terminal-spawn-restore'
const PANE_KEY = 'tab-1:leaf-1'
describe('seedHeadlessTerminalFromSpawnResult', () => {
afterEach(() => {
pendingByPaneKey.clear()
})
it('seeds main’s copy from a cold restore a window has declared, only when main owns the layout', () => {
const seedHeadlessTerminal = vi.fn()
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the seed calls only seedHeadlessTerminal.
const runtime = { seedHeadlessTerminal } as unknown as OrcaRuntimeService
pendingByPaneKey.set(PANE_KEY, { gen: 1, ownerWebContentsId: 7 })
seedHeadlessTerminalFromSpawnResult(
runtime,
{ id: 'pty-1', coldRestore: { scrollback: 'history', cwd: '/w' } },
PANE_KEY
)
// Main's copy is what a view repaints from later; the window holds nothing until it paints.
if (ORCA_LAYOUT_OWNER_IS_MAIN) {
expect(seedHeadlessTerminal).toHaveBeenCalledWith('pty-1', 'history', undefined, {
cwd: '/w',
oscLinks: undefined,
preferProviderIfExisting: true
})
} else {
expect(seedHeadlessTerminal).not.toHaveBeenCalled()
}
})
})
@@ -1,49 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
const switchState = vi.hoisted(() => ({ on: true }))
vi.mock('../../../../shared/layout-owner-switch', () => ({
get ORCA_LAYOUT_OWNER_IS_MAIN() {
return switchState.on
}
}))
import { rebindLocalProviderListeners } from './listener-lifecycle'
import { onLocalPtyProviderRebound } from './local-provider-rebound'
afterEach(() => {
switchState.on = true
})
describe('a replaced terminal provider (a terminal service restart)', () => {
it('tells main to show the live terminals it reports, in a layout-owner build', () => {
const listener = vi.fn()
const stop = onLocalPtyProviderRebound(listener)
rebindLocalProviderListeners()
stop()
rebindLocalProviderListeners()
expect(listener).toHaveBeenCalledOnce()
})
it('tells no one in a window-owned build', () => {
switchState.on = false
const listener = vi.fn()
const stop = onLocalPtyProviderRebound(listener)
rebindLocalProviderListeners()
stop()
expect(listener).not.toHaveBeenCalled()
})
it('one failing listener does not stop the others', () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
const later = vi.fn()
const stops = [
onLocalPtyProviderRebound(() => {
throw new Error('boom')
}),
onLocalPtyProviderRebound(later)
]
rebindLocalProviderListeners()
stops.forEach((stop) => stop())
expect(later).toHaveBeenCalledOnce()
})
})
@@ -1,45 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { getTrustedUIRendererWebContentsMock, handleMock } = vi.hoisted(() => ({
getTrustedUIRendererWebContentsMock: vi.fn(),
handleMock: vi.fn()
}))
vi.mock('electron', () => ({ ipcMain: { handle: handleMock } }))
vi.mock('./ui', () => ({
getTrustedUIRendererWebContents: getTrustedUIRendererWebContentsMock
}))
import { handleMainWindowSkillIpc } from './skill-ipc-main-window'
describe('main-window skill IPC', () => {
beforeEach(() => {
handleMock.mockReset()
getTrustedUIRendererWebContentsMock.mockReset()
})
it('allows the trusted main renderer', () => {
const listener = vi.fn(() => 'ok')
const sender = { id: 1 }
getTrustedUIRendererWebContentsMock.mockReturnValue(sender)
handleMainWindowSkillIpc('skills:test', listener)
const handler = handleMock.mock.calls[0][1]
expect(handler({ sender }, 'value')).toBe('ok')
expect(listener).toHaveBeenCalledWith({ sender }, 'value')
})
it.each([
['dashboard pop-out', { id: 2 }],
['stale renderer', { id: 3 }],
['missing main window', { id: 4 }]
])('rejects the %s before invoking skill code', (_label, sender) => {
const listener = vi.fn()
getTrustedUIRendererWebContentsMock.mockReturnValue(null)
handleMainWindowSkillIpc('skills:test', listener)
const handler = handleMock.mock.calls[0][1]
expect(() => handler({ sender }, 'value')).toThrow('Unauthorized skill IPC sender')
expect(listener).not.toHaveBeenCalled()
})
})
@@ -1,49 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { Store } from '../persistence'
import type { Repo } from '../../shared/repo-types'
const { listRepoWorktreesMock, getLocalProjectWorktreeGitOptionsMock } = vi.hoisted(() => ({
listRepoWorktreesMock: vi.fn(),
getLocalProjectWorktreeGitOptionsMock: vi.fn()
}))
vi.mock('../repo-worktrees', () => ({
createFolderWorktree: vi.fn(),
listRepoWorktrees: listRepoWorktreesMock
}))
vi.mock('../project-runtime-git-options', () => ({
getLocalProjectWorktreeGitOptions: getLocalProjectWorktreeGitOptionsMock
}))
import { scanWorkspaceCleanup } from './workspace-cleanup-scan'
const REPO: Repo = {
id: 'repo-1',
path: '/repo',
displayName: 'Repo',
badgeColor: '#000',
addedAt: 0
}
describe('workspace cleanup local Git routing', () => {
beforeEach(() => {
listRepoWorktreesMock.mockReset().mockResolvedValue([])
getLocalProjectWorktreeGitOptionsMock.mockReset()
})
it('uses the selected WSL distro while retaining the cleanup timeout signal', async () => {
const store = {
getRepos: () => [REPO]
} as Store
getLocalProjectWorktreeGitOptionsMock.mockReturnValue({ wslDistro: 'Ubuntu' })
await scanWorkspaceCleanup(store)
expect(getLocalProjectWorktreeGitOptionsMock).toHaveBeenCalledWith(store, REPO)
expect(listRepoWorktreesMock).toHaveBeenCalledWith(REPO, {
wslDistro: 'Ubuntu',
signal: expect.any(AbortSignal)
})
})
})
@@ -14,21 +14,4 @@ describe('finalized provider tail reservations', () => {
expect(reservation.reserve(16 * 1024 * 1024)).not.toBeNull()
expect(reservation.reserve(0)).toBeNull()
})
it('abandons outstanding reservations on close and refuses later admission', () => {
const reservation = new StructuredAgentSessionFinalTailReservation()
const release = reservation.reserve(100)
reservation.close()
release?.()
reservation.close()
expect(reservation.reserve(0)).toBeNull()
})
it('refuses invalid sizes', () => {
const reservation = new StructuredAgentSessionFinalTailReservation()
for (const bytes of [-1, 0.5, Number.NaN, Number.POSITIVE_INFINITY]) {
expect(reservation.reserve(bytes)).toBeNull()
}
expect(reservation.reserve(0)).not.toBeNull()
})
})
@@ -1,44 +0,0 @@
import { describe, expect, it } from 'vitest'
import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants'
import { reserveRequestFor, type AgentSessionAttachParams } from './structured-agent-session-attach'
const params: AgentSessionAttachParams = {
envelope: {
sessionId: 'chat-one',
clientOperationId: 'op-one',
expectedRuntimeFence: null,
payloadFingerprint: 'fingerprint'
},
location: {
executionHostId: 'local',
wslDistro: null,
workspaceId: FLOATING_TERMINAL_WORKTREE_ID,
workspaceKind: 'folder'
},
provider: 'claude',
agent: 'claude',
accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/host/account' },
runtimeKind: 'native'
}
describe('host-resolved directory in the attach reservation', () => {
it('carries the folder into the same required reservation as the record', () => {
const request = reserveRequestFor({
sessionId: params.envelope.sessionId,
params,
authority: {
spawnToken: 'spawn-one',
claimKeyId: 'claim-one',
handoffOperationId: null,
probe: { outcome: 'reservation-unused' },
launchDirectory: '/host/floating-folder'
},
callerKey: 'client-one',
fingerprint: 'fingerprint',
now: 123
})
expect(request.launchDirectory).toBe('/host/floating-folder')
expect(request.location.workspaceId).toBe(FLOATING_TERMINAL_WORKTREE_ID)
})
})
@@ -1,31 +0,0 @@
import { describe, expect, it } from 'vitest'
import { isRetryableDownloadError } from './transient-download-error'
function nodeError(message: string, code: string): Error {
return Object.assign(new Error(message), { code })
}
describe('isRetryableDownloadError', () => {
it("retries Chromium's dropped-connection errors", () => {
expect(isRetryableDownloadError(new Error('net::ERR_CONNECTION_RESET'))).toBe(true)
})
it.each([
['a response cut mid-body', nodeError('aborted', 'ECONNRESET')],
['a reset socket', nodeError('socket hang up', 'ECONNRESET')],
['a timed-out connect', nodeError('connect ETIMEDOUT 1.2.3.4:443', 'ETIMEDOUT')],
['a DNS hiccup', nodeError('getaddrinfo EAI_AGAIN example.com', 'EAI_AGAIN')],
['a DNS outage', nodeError('getaddrinfo ENOTFOUND example.com', 'ENOTFOUND')],
['a stream closed early', nodeError('Premature close', 'ERR_STREAM_PREMATURE_CLOSE')]
])("retries Node's %s", (_label, error) => {
expect(isRetryableDownloadError(error)).toBe(true)
})
it('does not retry a failure another attempt would repeat', () => {
expect(isRetryableDownloadError(nodeError('no such file', 'ENOENT'))).toBe(false)
expect(isRetryableDownloadError(new Error('Model downloads must use HTTPS'))).toBe(false)
expect(
isRetryableDownloadError(Object.assign(new Error('HTTP 404'), { httpStatusCode: 404 }))
).toBe(false)
})
})
@@ -1,42 +0,0 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { NODE_RUNTIME_ASSETS } from '../../shared/node-runtime-pin'
import { findAppImageNodeRuntime } from './appimage-bundled-node-runtime'
let resources = ''
beforeEach(() => {
resources = mkdtempSync(join(tmpdir(), 'orca-appimage-node-'))
})
afterEach(() => {
rmSync(resources, { recursive: true, force: true })
})
function bundle(): string {
const path = join(resources, 'node-runtime', 'bin', 'node')
mkdirSync(join(path, '..'), { recursive: true })
writeFileSync(path, '')
return path
}
describe('findAppImageNodeRuntime', () => {
it('names the pinned glibc Node a Linux package carries for its CPU', () => {
const path = bundle()
expect(findAppImageNodeRuntime(resources, 'arm64', 'linux')).toEqual({
path,
target: 'linux-arm64-glibc',
executableSha256: NODE_RUNTIME_ASSETS['linux-arm64-glibc'].executableSha256
})
})
it('finds nothing in a package without one, or off Linux', () => {
expect(findAppImageNodeRuntime(resources, 'x64', 'linux')).toBeNull()
bundle()
expect(findAppImageNodeRuntime(resources, 'x64', 'darwin')).toBeNull()
expect(findAppImageNodeRuntime(resources, 'ia32', 'linux')).toBeNull()
expect(findAppImageNodeRuntime(undefined, 'x64', 'linux')).toBeNull()
})
})
@@ -2,10 +2,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
readOrcadHostAccountLaunchEnv,
writeOrcadHostAccountLaunchEnv
} from './orcad-host-account-launch-env-store'
import { readOrcadHostAccountLaunchEnv } from './orcad-host-account-launch-env-store'
const dirs: string[] = []
function userData(): string {
@@ -21,17 +18,6 @@ afterEach(() => {
})
describe('orcad host account launch env store', () => {
it('round-trips what the desktop pushed', () => {
const dir = userData()
const launchEnv = {
wslDistro: 'Ubuntu',
claude: { CLAUDE_CONFIG_DIR: '/home/u/.orca/claude/a' },
terminal: { CODEX_HOME: '/home/u/.orca/codex/b' }
}
writeOrcadHostAccountLaunchEnv(dir, launchEnv)
expect(readOrcadHostAccountLaunchEnv(dir)).toEqual(launchEnv)
})
it('reads nothing from a missing, corrupt or unsafe file', () => {
const dir = userData()
expect(readOrcadHostAccountLaunchEnv(dir)).toBeNull()
@@ -1,32 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
classifyOrcadHostUnavailable,
orcadCandidateLaunchFailureCode
} from './orcad-host-unavailable'
import { OrcadWindowsLaunchRefusedError } from '../managed-server/install/orcad-remote-launch-windows'
import { OrcadWindowsCommandLineError } from '../managed-server/install/orcad-remote-windows-node'
describe('classifyOrcadHostUnavailable', () => {
it('sends a Windows host that cannot launch orcad back to the relay', () => {
const refused = new OrcadWindowsLaunchRefusedError('breakaway denied')
const unsafe = new OrcadWindowsCommandLineError('C:\\Users\\%x%')
expect(classifyOrcadHostUnavailable(refused)).toBe('unsupported_host')
expect(classifyOrcadHostUnavailable(unsafe)).toBe('unsupported_host')
expect(classifyOrcadHostUnavailable({ code: refused.code })).toBe('unsupported_host')
expect(classifyOrcadHostUnavailable({ code: unsafe.code })).toBe('unsupported_host')
})
it('keeps an ordinary launch failure retryable', () => {
expect(orcadCandidateLaunchFailureCode(new Error('spawn failed'))).toBe(
'orcad_candidate_launch_failed'
)
expect(
classifyOrcadHostUnavailable({
code: orcadCandidateLaunchFailureCode(new Error('spawn failed'))
})
).toBeNull()
expect(orcadCandidateLaunchFailureCode(new OrcadWindowsLaunchRefusedError('x'))).toBe(
'orcad_windows_launch_refused'
)
})
})
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it } from 'vitest'
import {
emitOrcadProfileStateAuthoritySelected,
formatOrcadProfileStateAuthoritySelected,
@@ -14,13 +14,6 @@ const selection: OrcadProfileStateAuthoritySelection = {
}
describe('orcad profile-state telemetry', () => {
it('formats a bounded machine-readable authority selection event', () => {
expect(JSON.parse(formatOrcadProfileStateAuthoritySelected(selection).slice(18))).toEqual({
event: 'profile_state_authority_selected',
...selection
})
})
it('strips unexpected runtime fields before writing the record', () => {
const selectionWithRuntimeFields = Object.assign({}, selection, {
database_path: '/private/profile-state.db'
@@ -29,13 +22,6 @@ describe('orcad profile-state telemetry', () => {
expect(line).not.toContain('database_path')
})
it('sends the event to the supplied sink', () => {
const sink = vi.fn()
emitOrcadProfileStateAuthoritySelected(selection, sink)
expect(sink).toHaveBeenCalledOnce()
expect(sink).toHaveBeenCalledWith(formatOrcadProfileStateAuthoritySelected(selection))
})
it('never lets a failing sink block startup', () => {
expect(() =>
emitOrcadProfileStateAuthoritySelected(selection, () => {
@@ -1,32 +0,0 @@
// wsl.exe --exec skips shell setup; hydrate login PATH to find Linux CLIs instead of Windows shims.
import { afterEach, describe, expect, it, vi } from 'vitest'
const hydration = vi.hoisted(() => ({
hydrateShellPath: vi.fn(async () => ({ ok: true as const, segments: ['/home/u/.local/bin'] })),
mergePathSegments: vi.fn(() => [])
}))
vi.mock('../startup/hydrate-shell-path', () => hydration)
import { getAppEnvironment } from '../../shared/app-environment'
import { hydrateShellPathForAgentDetection } from '../ipc/agent-detection-shell-path'
import { installOrcadHostAdapters } from './orcad-host-adapters'
describe('orcad PATH hydration on a WSL guest', () => {
const platform = process.platform
afterEach(() => {
Object.defineProperty(process, 'platform', { value: platform })
vi.clearAllMocks()
})
it('reports itself packaged, which is what gates the login-shell probe', () => {
installOrcadHostAdapters()
expect(getAppEnvironment().isPackaged()).toBe(true)
})
it('hydrates for detection even when a client names a WSL distro: inside it, Linux is local', async () => {
Object.defineProperty(process, 'platform', { value: 'linux' })
await hydrateShellPathForAgentDetection({ wslDistro: 'Ubuntu' })
expect(hydration.hydrateShellPath).toHaveBeenCalledTimes(1)
expect(hydration.mergePathSegments).toHaveBeenCalledWith(['/home/u/.local/bin'])
})
})
@@ -1,44 +0,0 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { resolveManagedSshHostLoginShell } from './managed-ssh-host-login-shell'
const hostPlatform = process.platform
const MANAGED = { ORCA_ORCAD_MANAGED_ACTIVATION_ROOT: 'C:\\Users\\u\\.orca-remote' }
const PWSH = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe'
const exists = () => true
describe('resolveManagedSshHostLoginShell', () => {
beforeEach(() => {
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
})
afterEach(() => {
Object.defineProperty(process, 'platform', { configurable: true, value: hostPlatform })
})
it('returns an existing PowerShell-family DefaultShell on a managed SSH host', () => {
expect(resolveManagedSshHostLoginShell(MANAGED, exists, () => PWSH)).toBe(PWSH)
})
it('never reads the registry for a desktop or user-started server', () => {
const read = () => {
throw new Error('must not read DefaultShell')
}
expect(resolveManagedSshHostLoginShell({}, exists, read)).toBeUndefined()
})
it('ignores a missing file and shells whose quoting family differs', () => {
expect(
resolveManagedSshHostLoginShell(
MANAGED,
() => false,
() => PWSH
)
).toBeUndefined()
for (const shell of [
'C:\\Windows\\System32\\cmd.exe',
'C:\\Program Files\\Git\\bin\\bash.exe',
''
]) {
expect(resolveManagedSshHostLoginShell(MANAGED, exists, () => shell)).toBeUndefined()
}
})
})
@@ -1,37 +0,0 @@
import { expect, it } from 'vitest'
import type { RuntimeMobileSessionTabCloseResult } from '../../shared/runtime-session-contracts'
import { describeMobileSessionTabCloseRefusal } from './mobile-session-tab-close-refusal-message'
const REASONS = [
'missing-intent',
'stale-publication',
'stale-terminal',
'live-host-pty',
'unknown-liveness',
'retirement-owner'
] as const
it.each(REASONS)('describes %s as a sentence, not an enum', (reason) => {
const message = describeMobileSessionTabCloseRefusal(reason)
expect(message).not.toContain(reason)
expect(message).toMatch(/^[A-Z].*\.$/)
})
it('falls back for a missing reason and for a reason only a newer host knows', () => {
const fallback = 'The host declined to close this terminal tab, so the tab was kept open.'
expect(describeMobileSessionTabCloseRefusal(undefined)).toBe(fallback)
// Newer hosts may return refusal reasons this client cannot name.
const fromNewerHost: RuntimeMobileSessionTabCloseResult = JSON.parse(
'{"closed":true,"refused":true,"refusalReason":"reason-from-the-future"}'
)
expect(describeMobileSessionTabCloseRefusal(fromNewerHost.refusalReason)).toBe(fallback)
})
it('avoids the substrings the Sleep-workspace toast reclassifies as an unreachable host', () => {
for (const reason of [...REASONS, undefined]) {
const message = describeMobileSessionTabCloseRefusal(reason)
for (const misleading of ['legacy', 'terminal_', 'runtime', 'connection', 'Daemon']) {
expect(message).not.toContain(misleading)
}
}
})
@@ -1,34 +0,0 @@
// Only main waking a sleeping pane substitutes for window restore and records agent resume outcome.
import { describe, expect, it, vi } from 'vitest'
import type { PaneResumeOutcome } from '../../shared/workspace-layout/workspace-layout-published'
import { setupLayoutOwnerRuntime, WORKTREE_ID } from './orca-runtime-layout-owner-start-fixture'
vi.mock('../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true }))
const RESUME = {
launchAgent: 'claude' as const,
resumeProviderSession: { key: 'session_id' as const, id: 'provider-session-1' }
}
async function resumedPaneOutcome(opts: { resumesSleepingRecord?: true }) {
const { runtime, spawn } = setupLayoutOwnerRuntime()
spawn.mockImplementation(
async (args: { onResumeOutcome?: (ptyId: string, outcome: PaneResumeOutcome) => void }) => {
args.onResumeOutcome?.('pty-1', 'restored')
return { id: 'pty-1' }
}
)
await runtime.createTerminal(`id:${WORKTREE_ID}`, { ...RESUME, ...opts })
const { tabId, leafId } = spawn.mock.calls[0]![0]
return runtime.resumeOutcomeOf(`${tabId}:${leafId}`)
}
describe("main's start records a pane's resume outcome (layout-owner build)", () => {
it("records it for a wake of the pane's sleeping record", async () => {
expect(await resumedPaneOutcome({ resumesSleepingRecord: true })).toBe('restored')
})
it('records nothing for a resume another client asked for (Session History, a phone)', async () => {
expect(await resumedPaneOutcome({})).toBeNull()
})
})
@@ -1,39 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { OrcaRuntimeService } from './orca-runtime'
import type { RuntimeNotifier } from './runtime-notifier-contract'
import type { TerminalPaneRevealTarget } from '../../shared/terminal-pane-reveal'
const target: TerminalPaneRevealTarget = {
worktreeId: 'repo-1::/srv/app',
tabId: 'tab-1',
leafId: null,
executionHostId: 'runtime:env-1'
}
function notifierWith(revealTerminalPane: RuntimeNotifier['revealTerminalPane']): RuntimeNotifier {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: revealTerminalPane reads only this member of the notifier.
return { revealTerminalPane } as RuntimeNotifier
}
describe('OrcaRuntimeService.revealTerminalPane', () => {
it('refuses on a runtime with no window, such as orca serve', async () => {
const runtime = new OrcaRuntimeService()
await expect(runtime.revealTerminalPane(target)).rejects.toThrow('renderer_unavailable')
})
it("reports the window's answer for the pane it was asked to show", async () => {
const runtime = new OrcaRuntimeService()
const revealTerminalPane = vi.fn(async () => false)
runtime.setNotifier(notifierWith(revealTerminalPane))
await expect(runtime.revealTerminalPane(target)).resolves.toEqual({
...target,
navigated: false
})
expect(revealTerminalPane).toHaveBeenCalledWith(target)
revealTerminalPane.mockResolvedValueOnce(true)
await expect(runtime.revealTerminalPane(target)).resolves.toMatchObject({ navigated: true })
})
})
@@ -16,16 +16,6 @@ function makeRuntime(): { runtime: OrcaRuntimeService; spawn: ReturnType<typeof
// Host-created panes need the same workspace id that renderer panes pass to agent wrappers.
describe('OrcaRuntimeService terminal ORCA_WORKSPACE_ID', () => {
it('stamps the worktree id on a git worktree terminal, as the window does', async () => {
const { runtime, spawn } = makeRuntime()
await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`, { title: 'phone shell' })
const env = spawnedPtyEnv(spawn.mock.calls[0]?.[0])
expect(env.ORCA_WORKSPACE_ID).toBe(TEST_WORKTREE_ID)
expect(env.ORCA_WORKSPACE_ID).toBe(env.ORCA_WORKTREE_ID)
})
it('replaces a client-sent value with the host workspace id', async () => {
const { runtime, spawn } = makeRuntime()
@@ -1,44 +0,0 @@
import { describe, expect, it } from 'vitest'
import { parseAllowStaleBaseFromSpec } from './coordinator-stale-base-flag'
describe('parseAllowStaleBaseFromSpec', () => {
it('matches canonical form on its own line and strips it', () => {
const spec = `Do the work
allow-stale-base: true`
const { allowStale, strippedSpec } = parseAllowStaleBaseFromSpec(spec)
expect(allowStale).toBe(true)
expect(strippedSpec).toBe('Do the work\n')
expect(strippedSpec).not.toContain('allow-stale-base')
})
it('matches case-insensitively', () => {
const spec = `Do the work
Allow-Stale-Base: TRUE`
const { allowStale, strippedSpec } = parseAllowStaleBaseFromSpec(spec)
expect(allowStale).toBe(true)
expect(strippedSpec).not.toMatch(/[Aa]llow-[Ss]tale-[Bb]ase/)
})
it('does not match allow-stale-base: false', () => {
const spec = `Do the work
allow-stale-base: false`
const { allowStale, strippedSpec } = parseAllowStaleBaseFromSpec(spec)
expect(allowStale).toBe(false)
expect(strippedSpec).toBe(spec)
})
it('does not match allow-stale-base: truthy', () => {
const spec = `Do the work
allow-stale-base: truthy`
const { allowStale, strippedSpec } = parseAllowStaleBaseFromSpec(spec)
expect(allowStale).toBe(false)
expect(strippedSpec).toBe(spec)
})
it('does not match the flag embedded inside a sentence', () => {
const spec = 'we allow-stale-base: true sometimes'
const { allowStale, strippedSpec } = parseAllowStaleBaseFromSpec(spec)
expect(allowStale).toBe(false)
expect(strippedSpec).toBe(spec)
})
})
@@ -1,48 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { MessageRow } from '../types'
import {
legacyMessageMatchesQuestion,
normalizeLegacyQuestionOptions,
normalizeLegacyQuestionText
} from './legacy-question-identity'
function message(overrides: Partial<MessageRow> = {}): MessageRow {
return {
id: 'msg_1',
run_id: 'run_1',
delivery_contract: 'legacy_direct',
from_handle: 'from',
to_handle: 'to',
subject: 'q',
body: 'Ask this?\r\n',
type: 'question',
priority: 'normal',
thread_id: null,
payload: '{"options":[" yes ","no"]}',
read: 0,
sequence: 1,
created_at: '2026-01-01 00:00:00',
delivered_at: null,
sender_pane_key: null,
...overrides
}
}
describe('legacy-question-identity', () => {
it('normalizes question text and option arrays', () => {
expect(normalizeLegacyQuestionText(' a\r\nb ')).toBe('a\nb')
expect(normalizeLegacyQuestionOptions([' yes ', 'no'])).toBe('["yes","no"]')
expect(normalizeLegacyQuestionOptions(['yes', 1])).toBe('[]')
})
it('matches a question only when recipient, body, and options agree', () => {
expect(legacyMessageMatchesQuestion(message(), 'Ask this?', ['yes', 'no'], ['to'])).toBe(true)
expect(legacyMessageMatchesQuestion(message(), 'Ask this?', ['yes', 'no'], ['other'])).toBe(
false
)
expect(legacyMessageMatchesQuestion(message(), 'Different', ['yes', 'no'], ['to'])).toBe(false)
expect(
legacyMessageMatchesQuestion(message({ payload: '{' }), 'Ask this?', ['yes'], ['to'])
).toBe(false)
})
})
@@ -1,48 +0,0 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import Database from '../../sqlite/sync-database'
import { OrchestrationDb } from './db'
import { SCHEMA_VERSION } from './db/contract-constants'
describe('orchestration migration from every prior version stamp', () => {
const tempDirs: string[] = []
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true })
}
})
it('opens and reopens a complete schema stamped at every prior version', () => {
for (let version = 0; version < SCHEMA_VERSION; version += 1) {
const dir = mkdtempSync(join(tmpdir(), `orca-migration-v${version}-`))
tempDirs.push(dir)
const dbPath = join(dir, 'orchestration.db')
new OrchestrationDb(dbPath).close()
const stamped = new Database(dbPath)
stamped.pragma(`user_version = ${version}`)
stamped.close()
const migrated = new OrchestrationDb(dbPath)
expect(migrated.db.pragma('user_version', { simple: true }), `v${version}`).toBe(
SCHEMA_VERSION
)
migrated.close()
const reopened = new OrchestrationDb(dbPath)
expect(reopened.db.pragma('user_version', { simple: true }), `reopen v${version}`).toBe(
SCHEMA_VERSION
)
expect(() =>
reopened.createTask({
runId: 'run_legacy_local',
spec: `migration v${version}`
})
).not.toThrow()
reopened.close()
}
})
})
@@ -27,12 +27,4 @@ describe('waitForPtyExitRecord', () => {
await expect(wait).resolves.toBe(false)
runtime.onPtyExit(PTY_ID, 0)
})
it('does not wait for a PTY the runtime never registered or already saw exit', async () => {
const runtime = new OrcaRuntimeService()
await expect(runtime.waitForPtyExitRecord('unknown-pty', 10_000)).resolves.toBe(true)
runtime.registerPty(PTY_ID, WORKTREE_ID, null)
runtime.onPtyExit(PTY_ID, 0)
await expect(runtime.waitForPtyExitRecord(PTY_ID, 10_000)).resolves.toBe(true)
})
})
@@ -1,41 +0,0 @@
import { createHash } from 'node:crypto'
import { expect, it } from 'vitest'
import { PushGatewayClient } from './push-gateway-client'
import { buildPushChallengeFixture, createPushHostKeypair } from './push-host-challenge-fixtures'
it('retains a delete when its session proof expires before the DELETE is attempted', async () => {
const keypair = createPushHostKeypair()
const hostFingerprint = createHash('sha256')
.update(keypair.publicKey)
.digest('base64url')
.slice(0, 16)
let now = 1_770_000_000_000
let deletes = 0
const client = new PushGatewayClient({
gatewayUrl: 'https://push.example.test',
keypair,
now: () => now,
fetch: (async (url, init) => {
if (String(url).endsWith('/challenge')) {
const fixture = buildPushChallengeFixture({
hostKeypair: keypair,
hostFingerprint,
gatewayOrigin: 'https://push.example.test',
issuedAt: now,
challengeId: 'challenge-1'
})
now += 11_000
return Response.json(fixture.challenge)
}
if (String(url).endsWith('/session')) {
return Response.json({ error: 'invalid_proof' }, { status: 401 })
}
if (init?.method === 'DELETE') {
deletes++
}
return new Response(null, { status: 204 })
}) as typeof fetch
})
expect(await client.deleteDevice('registration-1')).toEqual(false)
expect(deletes).toBe(0)
})
@@ -1,41 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { CODEX_REMOTE_VIEWER_SSH_CONNECTION } from '../ipc/pty/host-env/codex-terminal-clipboard'
import { applyRemoteViewerLaunchEnv } from './remote-viewer-launch-env'
afterEach(() => vi.unstubAllEnvs())
describe('applyRemoteViewerLaunchEnv', () => {
it.each([true, false])('marks a remote caller’s Codex (image support %s)', (supported) => {
vi.stubEnv('SSH_CONNECTION', undefined)
vi.stubEnv('SSH_TTY', undefined)
const launch = { launchAgent: 'codex' as const, env: { KEEP: '1' } }
expect(applyRemoteViewerLaunchEnv(launch, supported).env).toEqual({
KEEP: '1',
SSH_CONNECTION: CODEX_REMOTE_VIEWER_SSH_CONNECTION
})
expect(launch.env).toEqual({ KEEP: '1' })
})
it('leaves a launch from this host untouched', () => {
const launch = { launchAgent: 'codex' as const }
expect(applyRemoteViewerLaunchEnv(launch, undefined)).toBe(launch)
})
it('keeps an SSH session the launch already carries', () => {
const launch = {
launchAgent: 'codex' as const,
env: { SSH_CONNECTION: '10.0.0.1 1 10.0.0.2 22' }
}
expect(applyRemoteViewerLaunchEnv(launch, true)).toBe(launch)
})
it('still applies the Claude image rule and never marks Claude', () => {
vi.stubEnv('CLAUDE_CODE_FORCE_TERMINAL_IMAGES', undefined)
const launch: { launchAgent: 'claude'; env?: Record<string, string> } = {
launchAgent: 'claude'
}
expect(applyRemoteViewerLaunchEnv(launch, false).env).toEqual({
CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '0'
})
})
})
@@ -1,38 +0,0 @@
import { describe, expect, it } from 'vitest'
import { RUNTIME_NAVIGATION_TARGETS } from '../../../../shared/runtime-navigation'
import { BrowserTabCreateParams } from '../../../../shared/rpc-contract/browser-tab-create-params'
describe('browser.tabCreate placement schema', () => {
it('keeps placement optional for older clients', () => {
expect(BrowserTabCreateParams.parse({ worktree: 'id:worktree-a' })).not.toHaveProperty(
'placement'
)
})
it.each([
{ kind: 'server' as const },
{ kind: 'client' as const, browserHostClientId: 'browser-client-a' }
])('accepts additive explicit $kind placement', (placement) => {
expect(BrowserTabCreateParams.parse({ placement })).toMatchObject({ placement })
})
it('rejects malformed client placement identity', () => {
expect(() =>
BrowserTabCreateParams.parse({ placement: { kind: 'client', browserHostClientId: '' } })
).toThrow()
})
it('keeps navigation optional so a client that predates it still parses', () => {
expect(BrowserTabCreateParams.parse({ worktree: 'id:worktree-a' })).not.toHaveProperty(
'navigation'
)
})
it.each(RUNTIME_NAVIGATION_TARGETS)('accepts the additive %s navigation target', (navigation) => {
expect(BrowserTabCreateParams.parse({ navigation })).toMatchObject({ navigation })
})
it('rejects a navigation target the host does not define', () => {
expect(() => BrowserTabCreateParams.parse({ navigation: 'others' })).toThrow()
})
})
@@ -1,32 +0,0 @@
import '../unused-default-rpc-methods.test-fixture'
import { expect, it, vi } from 'vitest'
import type { OrcaRuntimeService } from '../../orca-runtime'
import { RpcDispatcher } from '../dispatcher'
import { JIRA_METHODS } from './jira'
it('keeps verified reads and combined board filters in separate public argument positions', async () => {
const jiraListIssues = vi.fn().mockResolvedValue([])
const stub = { getRuntimeId: () => 'board-runtime', jiraListIssues }
const dispatcher = new RpcDispatcher({
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This test dispatches only the fixture's Jira list method.
runtime: stub as unknown as OrcaRuntimeService,
methods: JIRA_METHODS
})
const filters = { statuses: ['Blocked', 'In Progress'], currentSprint: true }
const response = await dispatcher.dispatch({
id: 'board-filter',
authToken: 'fixture',
method: 'jira.listIssues',
params: { filter: 'all', limit: 20, siteId: 'site-a', strict: true, filters }
})
expect(response).toMatchObject({ ok: true, result: [] })
expect(jiraListIssues).toHaveBeenCalledWith('all', 20, 'site-a', true, filters)
await dispatcher.dispatch({
id: 'legacy-list',
authToken: 'fixture',
method: 'jira.listIssues',
params: { filter: 'all', limit: 20, siteId: 'site-a' }
})
expect(jiraListIssues).toHaveBeenLastCalledWith('all', 20, 'site-a', undefined, undefined)
})
@@ -1,38 +0,0 @@
import '../../../unused-default-rpc-methods.test-fixture'
import { afterEach, describe, expect, it } from 'vitest'
import type { RpcRequest } from '../../../core'
import { ORCHESTRATION_METHODS } from '../../orchestration'
import { RpcDispatcher } from '../../../dispatcher'
import { createOrchestrationRpcHarness } from '../rpc-test-harness'
import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../../shared/protocol-version'
describe('orchestration.send invalid message type', () => {
const h = createOrchestrationRpcHarness()
afterEach(() => {
h.cleanup()
})
it('explains valid message types and the question reply path', async () => {
const { runtime, ctx } = h.setup()
const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS })
const request: RpcRequest = {
id: 'req_1',
authToken: 'token',
method: 'orchestration.send',
params: { to: 'b', subject: 'hi', type: 'answer' },
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION
}
const response = await dispatcher.dispatch(request, ctx)
expect(response).toMatchObject({
ok: false,
error: {
code: 'invalid_argument',
message:
'Invalid --type. Expected one of: status, dispatch, worker_done, merge_ready, escalation, handoff, decision_gate, question, heartbeat. To answer a worker question, use the same Orca CLI executable with orchestration reply --id <msg_id> --body <text>.'
}
})
})
})
@@ -1,9 +1,6 @@
import { describe, expect, it } from 'vitest'
import { MAX_TIMER_DELAY_MS } from '../../../../../../shared/timer-delay'
import {
ORCHESTRATION_READINESS_TIMEOUT_MS,
ORCHESTRATION_WORKER_START_CLIENT_GRACE_MS
} from '../../../../../../shared/orchestration-timing-budgets'
import { ORCHESTRATION_WORKER_START_CLIENT_GRACE_MS } from '../../../../../../shared/orchestration-timing-budgets'
import { resolveFederatedWorkerStartBudgets } from './worker-start-budgets'
describe('worker-start transport budgets', () => {
@@ -19,16 +16,4 @@ describe('worker-start transport budgets', () => {
'derived timeout must fit'
)
})
it('normalizes non-positive requests to the ordinary readiness default', () => {
const expectedOuterDeadline =
1_000 + ORCHESTRATION_READINESS_TIMEOUT_MS + ORCHESTRATION_WORKER_START_CLIENT_GRACE_MS
expect(resolveFederatedWorkerStartBudgets(0, 1_000).readinessTimeoutMs).toBe(
ORCHESTRATION_READINESS_TIMEOUT_MS
)
expect(resolveFederatedWorkerStartBudgets(0, 1_000).outerDeadlineMs).toBe(expectedOuterDeadline)
expect(resolveFederatedWorkerStartBudgets(-1, 1_000).outerDeadlineMs).toBe(
expectedOuterDeadline
)
})
})
@@ -1,30 +0,0 @@
import { describe, expect, it } from 'vitest'
import { isUnknownWorkerStartOutcome } from './worker-topology'
describe('worker start outcome classification', () => {
it('treats an explicit operation_unknown code as unknown at any stage', () => {
const error = Object.assign(new Error('relay dropped'), { code: 'operation_unknown' })
expect(isUnknownWorkerStartOutcome(error, 'dispatch_input')).toBe(true)
expect(isUnknownWorkerStartOutcome(error, 'worktree_create')).toBe(true)
})
it('treats a lost connection during worktree create as unknown', () => {
expect(isUnknownWorkerStartOutcome(new Error('connection reset'), 'worktree_create')).toBe(true)
expect(isUnknownWorkerStartOutcome(new Error('request timed out'), 'worktree_create')).toBe(
true
)
})
it('keeps a definite failure definite', () => {
expect(isUnknownWorkerStartOutcome(new Error('connection reset'), 'dispatch_input')).toBe(false)
expect(isUnknownWorkerStartOutcome(new Error('worktree exists'), 'worktree_create')).toBe(false)
})
// Stalled prompts retain definite failure: the worker's later report can re-settle using its preserved capability (worker-start-unobserved-prompt-settlement.test.ts).
it('does not class a stalled dispatch prompt as unknown', () => {
expect(isUnknownWorkerStartOutcome(new Error('agent_prompt_stalled'), 'dispatch_input')).toBe(
false
)
})
})
@@ -1,39 +0,0 @@
import '../unused-default-rpc-methods.test-fixture'
import { describe, expect, it } from 'vitest'
import { RpcDispatcher } from '../dispatcher'
import { OrcaRuntimeService } from '../../orca-runtime'
import { SSH_TARGET_MANAGEMENT_UNSERVED_MESSAGE } from '../../../ssh/targets/ssh-target-registry'
import { SSH_METHODS } from './ssh'
const target = { label: 'Build', host: 'build.internal', port: 22, username: 'ci' }
// orcad advertises target-management without SSH handlers; refuse with text released clients can display (D3).
describe('SSH target management on a host with no SSH stack', () => {
const runtime = new OrcaRuntimeService()
const dispatch = (method: string, params?: unknown) =>
new RpcDispatcher({ runtime, methods: SSH_METHODS }).dispatch({
id: 'req-1',
authToken: 'tok',
method,
params
})
it.each([
['ssh.addTarget', { target }],
['ssh.updateTarget', { targetId: 'ssh-1', target }],
['ssh.removeTarget', { targetId: 'ssh-1' }],
['ssh.browseDir', { targetId: 'ssh-1', dirPath: '~' }]
])('%s refuses with an accurate message', async (method, params) => {
expect(await dispatch(method, params)).toMatchObject({
ok: false,
error: { code: 'runtime_error', message: SSH_TARGET_MANAGEMENT_UNSERVED_MESSAGE }
})
})
it('still lists no targets rather than failing', async () => {
expect(await dispatch('ssh.listEditableTargets')).toMatchObject({
ok: true,
result: { targets: [] }
})
})
})
@@ -10,31 +10,10 @@ function readParams() {
}
describe('terminal.read screen and cursor', () => {
// RPC callers can bypass the CLI's screen/cursor exclusion; reject mixed rendered-line and stream-pagination frames.
it('rejects a cursor combined with a screen read', () => {
expect(() => readParams().parse({ terminal: 'term_abc', screen: true, cursor: 42 })).toThrow(
/Cursor cannot be combined with a screen read/
)
})
it('still accepts each on its own', () => {
expect(readParams().parse({ terminal: 'term_abc', screen: true })).toMatchObject({
screen: true
})
expect(readParams().parse({ terminal: 'term_abc', cursor: 42 })).toMatchObject({ cursor: 42 })
})
// Cursor zero is present too; reject the combination on the first page.
it('rejects cursor zero with a screen read', () => {
expect(() => readParams().parse({ terminal: 'term_abc', screen: true, cursor: 0 })).toThrow(
/Cursor cannot be combined with a screen read/
)
})
it('leaves an ordinary paginated read untouched', () => {
expect(readParams().parse({ terminal: 'term_abc', cursor: 0, limit: 100 })).toMatchObject({
cursor: 0,
limit: 100
})
})
})
@@ -3,20 +3,6 @@ import { OrcaRuntimeService } from './orca-runtime'
export function registerRuntimeTerminalClientUseTests(): void {
describe('readTerminalClientUse', () => {
it('reads a spawned terminal nobody typed into or views as unused', () => {
const runtime = new OrcaRuntimeService()
runtime.terminalRunFacts.recordSpawnCommit({ id: 'pty-1' })
runtime.terminalRunFacts.recordInput('pty-1', 'launch', 'claude "run checks"\r')
expect(runtime.readTerminalClientUse('pty-1')).toBe('unused')
})
it('reads a terminal a client typed into as used', () => {
const runtime = new OrcaRuntimeService()
runtime.terminalRunFacts.recordSpawnCommit({ id: 'pty-1' })
runtime.terminalRunFacts.recordInput('pty-1', 'driving', 'git status\r')
expect(runtime.readTerminalClientUse('pty-1')).toBe('used')
})
it('reads a terminal a client is viewing as used', () => {
const runtime = new OrcaRuntimeService()
runtime.terminalRunFacts.recordSpawnCommit({ id: 'pty-1' })
@@ -26,10 +12,5 @@ export function registerRuntimeTerminalClientUseTests(): void {
release()
expect(runtime.readTerminalClientUse('pty-1')).toBe('unused')
})
it('cannot tell for a terminal this process adopted rather than spawned', () => {
const runtime = new OrcaRuntimeService()
expect(runtime.readTerminalClientUse('pty-adopted')).toBe('unknown')
})
})
}
@@ -1,44 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import type { EnrichedAgentHookEventPayload } from '../../../agent-hooks/server/server-types'
import { subscribeHookStatusTitles } from './hook-status-title-subscription'
const layoutOwner = vi.hoisted(() => ({ isMain: true }))
vi.mock('../../../../shared/layout-owner-switch', () => ({
get ORCA_LAYOUT_OWNER_IS_MAIN() {
return layoutOwner.isMain
}
}))
function hookServer() {
const listeners: ((row: EnrichedAgentHookEventPayload) => void)[] = []
return {
listeners,
subscribeEnrichedStatus: vi.fn((listener: (row: EnrichedAgentHookEventPayload) => void) => {
listeners.push(listener)
return () => listeners.splice(listeners.indexOf(listener), 1)
})
}
}
describe('main’s generated titles from hook status', () => {
it('follows every status in a layout-owner build, until unsubscribed', () => {
layoutOwner.isMain = true
const server = hookServer()
const runtime = { recordHookStatusTitle: vi.fn() }
const unsubscribe = subscribeHookStatusTitles(server, runtime)
expect(server.listeners).toHaveLength(1)
unsubscribe()
expect(server.listeners).toHaveLength(0)
})
it('subscribes to nothing with the switch off, where the window titles its tabs', () => {
layoutOwner.isMain = false
const server = hookServer()
subscribeHookStatusTitles(server, { recordHookStatusTitle: vi.fn() })
expect(server.subscribeEnrichedStatus).not.toHaveBeenCalled()
})
})
@@ -1,48 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { runLayoutPaneStarts, stopReplacedTerminals } from './layout-command-pane-starts'
const LEAF = '11111111-1111-4111-8111-111111111111'
const PANE_KEY = `tab-1:${LEAF}`
describe('runLayoutPaneStarts', () => {
it('starts each named pane through the starter', async () => {
const start = vi.fn(async () => ({ id: 'pty-1' }))
runLayoutPaneStarts(
{ type: 'restartPane', workspace: 'wt' },
{ stopPtyIds: ['pty-old'], startPaneKeys: [PANE_KEY] },
start
)
await vi.waitFor(() =>
expect(start).toHaveBeenCalledExactlyOnceWith({
worktreeId: 'wt',
tabId: 'tab-1',
leafId: LEAF
})
)
})
it('runs no start for a create, which starts through its own path', () => {
const start = vi.fn(async () => ({ id: 'pty-1' }))
runLayoutPaneStarts(
{ type: 'createTerminalTab', workspace: 'wt' },
{ stopPtyIds: [], startPaneKeys: [PANE_KEY] },
start
)
expect(start).not.toHaveBeenCalled()
})
})
describe('stopReplacedTerminals', () => {
it('stops every replaced terminal', () => {
const stop = vi.fn(() => true)
expect(stopReplacedTerminals(['pty-a', 'pty-b'], stop)).toBe(true)
expect(stop.mock.calls).toEqual([['pty-a'], ['pty-b']])
})
it('says so when a terminal would not stop', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
expect(stopReplacedTerminals(['pty-old'], () => false)).toBe(false)
expect(warn).toHaveBeenCalled()
warn.mockRestore()
})
})
@@ -1,40 +0,0 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import type { TuiAgent } from '../../shared/tui-agent'
import { ptyTuiIdleEvidence, type TuiIdleEvidenceSource } from './tui-idle-evidence-source'
import { makeTuiIdlePty } from './tui-idle-wait-test-harness'
vi.mock('electron', () => ({
BrowserWindow: { fromId: vi.fn(() => null) },
webContents: { fromId: vi.fn(() => null) },
ipcMain: { on: vi.fn(), removeListener: vi.fn() },
app: { getPath: vi.fn(() => '/tmp') }
}))
function source(agent: TuiAgent): TuiIdleEvidenceSource {
return {
quiescenceMs: 3000,
getTabTitle: () => null,
getAdoptedPtyIdleStatus: () => 'idle',
getPaneAgent: () => agent,
getFirstPartyAgentStatus: () => null,
readScreenLines: () => null
}
}
describe('ptyTuiIdleEvidence', () => {
it.each([
['qoder', 'qoder-trust-dialog'],
['qoder-cn', 'qoder-cn-signin']
] as const)('requires a live composer for adopted %s panes', (agent, fixture) => {
const transcript = readFileSync(join(__dirname, '__fixtures__', `${fixture}.txt`), 'utf8')
const evidence = ptyTuiIdleEvidence(source(agent), makeTuiIdlePty(), () => transcript)
expect(evidence.readPositiveBodyEvidence()).toBe(false)
})
it('keeps adopted idle evidence for other agents', () => {
const evidence = ptyTuiIdleEvidence(source('claude'), makeTuiIdlePty(), () => '')
expect(evidence.readPositiveBodyEvidence()).toBe(true)
})
})
@@ -1,43 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { gitExecFileAsyncMock, findExistingWorktreeSymlinkPathsMock } = vi.hoisted(() => ({
gitExecFileAsyncMock: vi.fn(),
findExistingWorktreeSymlinkPathsMock: vi.fn()
}))
vi.mock('../github/gh-utils', () => ({
acquire: vi.fn(),
release: vi.fn(),
ghExecFileAsync: vi.fn(),
gitExecFileAsync: gitExecFileAsyncMock
}))
vi.mock('../git/worktree-symlink-detection', () => ({
findExistingWorktreeSymlinkPaths: findExistingWorktreeSymlinkPathsMock
}))
import { hasUncommittedChanges } from './hosted-review-creation-git-state'
// Git reports guest paths; shared-symlink lstat needs host spelling or WSL reviews stay falsely dirty.
describe('hasUncommittedChanges shared-symlink probe', () => {
beforeEach(() => {
gitExecFileAsyncMock.mockReset()
findExistingWorktreeSymlinkPathsMock.mockReset()
gitExecFileAsyncMock.mockResolvedValue({ stdout: '?? node_modules\0', stderr: '' })
findExistingWorktreeSymlinkPathsMock.mockResolvedValue(['node_modules'])
})
it('passes the configured distro through to the probe', async () => {
await expect(
hasUncommittedChanges('/home/me/repo/feature', 'local', {
localGitExecOptions: { wslDistro: 'Ubuntu' },
sharedLinkPaths: ['node_modules']
})
).resolves.toBe(false)
expect(findExistingWorktreeSymlinkPathsMock).toHaveBeenCalledWith(
'/home/me/repo/feature',
['node_modules'],
{ wslDistro: 'Ubuntu' }
)
})
})
@@ -1,41 +0,0 @@
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { resolveFile, resolveTokens } from './stt-worker-model-config'
const MODEL_DIR = join('models', 'test-model')
describe('resolveFile', () => {
it('resolves an encoder/decoder/joiner triple by role name', () => {
const files = ['encoder.int8.onnx', 'decoder.int8.onnx', 'joiner.int8.onnx', 'tokens.txt']
expect(resolveFile(files, 'encoder', MODEL_DIR)).toBe(join(MODEL_DIR, 'encoder.int8.onnx'))
expect(resolveFile(files, 'decoder', MODEL_DIR)).toBe(join(MODEL_DIR, 'decoder.int8.onnx'))
expect(resolveFile(files, 'joiner', MODEL_DIR)).toBe(join(MODEL_DIR, 'joiner.int8.onnx'))
})
it('resolves a single fused model file for nemo-ctc-style manifests', () => {
const files = ['model.int8.onnx', 'tokens.txt']
expect(resolveFile(files, 'model', MODEL_DIR)).toBe(join(MODEL_DIR, 'model.int8.onnx'))
})
it('throws when no file matches the requested role', () => {
const files = ['model.int8.onnx', 'tokens.txt']
expect(() => resolveFile(files, 'joiner', MODEL_DIR)).toThrow(/No \*joiner\*\.onnx found/)
})
})
describe('resolveTokens', () => {
it('resolves tokens.txt regardless of surrounding files', () => {
const files = ['model.int8.onnx', 'tokens.txt']
expect(resolveTokens(files, MODEL_DIR)).toBe(join(MODEL_DIR, 'tokens.txt'))
})
it('throws when tokens.txt is missing', () => {
const files = ['model.int8.onnx']
expect(() => resolveTokens(files, MODEL_DIR)).toThrow(/No \*tokens\.txt found/)
})
})
-37
View File
@@ -1,37 +0,0 @@
import { join } from 'node:path'
import { afterEach, expect, it, vi } from 'vitest'
vi.mock('../../shared/app-environment', () => ({
getAppEnvironment: () => {
throw new Error('AppEnvironment not initialized')
}
}))
import { relayBundleCandidates } from './relay-bundle-paths'
afterEach(() => vi.unstubAllEnvs())
it('lists the WSL guest bundle dirs in the order the WSL relays searched them', () => {
vi.stubEnv('ORCA_RELAY_PATH', join('/env', 'relay'))
const resources = Object.getOwnPropertyDescriptor(process, 'resourcesPath')
Object.defineProperty(process, 'resourcesPath', { value: '/res', configurable: true })
try {
expect(relayBundleCandidates('wsl', '/app')).toEqual([
join('/env', 'relay', 'wsl'),
join('/res', 'relay', 'wsl'),
join('/res', 'app.asar.unpacked', 'out', 'relay', 'wsl'),
join('/app', 'resources', 'relay', 'wsl'),
join('/app', 'out', 'relay', 'wsl')
])
// No app environment (tests, early startup): the env and resources dirs still resolve.
expect(relayBundleCandidates('wsl')).toEqual([
join('/env', 'relay', 'wsl'),
join('/res', 'relay', 'wsl'),
join('/res', 'app.asar.unpacked', 'out', 'relay', 'wsl')
])
} finally {
if (resources) {
Object.defineProperty(process, 'resourcesPath', resources)
} else {
Reflect.deleteProperty(process, 'resourcesPath')
}
}
})
-16
View File
@@ -24,20 +24,4 @@ describe('classifyError', () => {
)
).toEqual({ error_class: 'unknown' })
})
it('returns unknown for null/undefined input', () => {
expect(classifyError(null)).toEqual({ error_class: 'unknown' })
expect(classifyError(undefined)).toEqual({ error_class: 'unknown' })
})
it('returns unknown for an unrecognized message', () => {
expect(classifyError(new Error('some unique failure mode we do not know'))).toEqual({
error_class: 'unknown'
})
})
it('returns unknown for non-Error throws', () => {
expect(classifyError('a bare string')).toEqual({ error_class: 'unknown' })
expect(classifyError({ random: 'object' })).toEqual({ error_class: 'unknown' })
})
})
@@ -1,37 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { UsageWorktreeRef } from '../usage-worktree-metadata'
import { getUsageWorktreeFingerprint } from './usage-worktree-refs'
function worktree(worktreeId: string, path: string, displayName: string): UsageWorktreeRef {
return { worktreeId, path, displayName }
}
describe('getUsageWorktreeFingerprint', () => {
it('is stable across repo and worktree ordering but changes with identity metadata', () => {
const first = new Map<string, UsageWorktreeRef[]>([
[
'repo-b',
[
worktree('repo-b::/repo/b-two', '/repo/b-two', 'B Two'),
worktree('repo-b::/repo/b-one', '/repo/b-one', 'B One')
]
],
['repo-a', [worktree('repo-a::/repo/a', '/repo/a', 'A')]]
])
const reordered = new Map<string, UsageWorktreeRef[]>([
['repo-a', [worktree('repo-a::/repo/a', '/repo/a', 'A')]],
[
'repo-b',
[
worktree('repo-b::/repo/b-one', '/repo/b-one', 'B One'),
worktree('repo-b::/repo/b-two', '/repo/b-two', 'B Two')
]
]
])
const renamed = new Map(reordered)
renamed.set('repo-a', [worktree('repo-a::/repo/a', '/repo/a', 'Renamed A')])
expect(getUsageWorktreeFingerprint(first)).toBe(getUsageWorktreeFingerprint(reordered))
expect(getUsageWorktreeFingerprint(renamed)).not.toBe(getUsageWorktreeFingerprint(first))
})
})
@@ -1,36 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import type { IpcMainInvokeEvent } from 'electron'
const native = vi.hoisted(() => ({ visible: true, minimized: false, destroyed: false }))
vi.mock('../runtime/runtime-desktop-surface', () => ({
getRuntimeDesktopSurface: () => ({
isResourceViewVisible: () => !native.destroyed && native.visible && !native.minimized
})
}))
import { assertResourceViewVisible } from './resource-view-admission'
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The mocked window resolver only requires a sender placeholder.
const event = { sender: {} } as IpcMainInvokeEvent
describe('native diagnostic dispatch veto', () => {
it.each([
[false, false, false],
[true, true, false],
[true, false, true]
])(
'rejects hidden/minimized/destroyed windows before collection: %s %s %s',
(visible, minimized, destroyed) => {
Object.assign(native, { visible, minimized, destroyed })
const provider = vi.fn()
const collect = () => {
assertResourceViewVisible(event, { resourceManagerView: true })
provider()
}
expect(collect).toThrow('view_not_visible')
expect(provider).not.toHaveBeenCalled()
expect(() => assertResourceViewVisible(event)).not.toThrow()
}
)
it('admits a visible window without requiring focus', () => {
Object.assign(native, { visible: true, minimized: false, destroyed: false })
expect(() => assertResourceViewVisible(event, { resourceManagerView: true })).not.toThrow()
})
})
@@ -1,30 +1,10 @@
import { describe, expect, it } from 'vitest'
import { WorkspaceSpaceScanCapacityError } from '../shared/workspace-space-scan-budget'
import {
WorkspaceSpaceScanCancelledError,
classifyWorkspaceSpaceError,
createWorkspaceSpaceScanLimiter
} from './workspace-space-scan-control'
describe('workspace space scan boundaries', () => {
it.each([
[{ code: 'ENOENT', message: 'gone' }, 'missing'],
[{ code: 'ENOTDIR', message: 'not a directory' }, 'missing'],
[{ code: 'EACCES', message: 'denied' }, 'permission-denied'],
[{ code: 'EPERM', message: 'denied' }, 'permission-denied'],
[new Error('other'), 'error']
] as const)('classifies %o as %s without changing error semantics', (error, status) => {
expect(classifyWorkspaceSpaceError(error).status).toBe(status)
})
it('keeps capacity exhaustion distinct from filesystem errors', () => {
const error = new WorkspaceSpaceScanCapacityError({ maxEntries: 1, maxRetainedBytes: 1 })
expect(classifyWorkspaceSpaceError(error)).toEqual({
status: 'unavailable',
message: error.message
})
})
it('rejects queued work with the public cancellation error', async () => {
const controller = new AbortController()
const limit = createWorkspaceSpaceScanLimiter(1, controller.signal)
@@ -36,6 +36,7 @@ export async function addHostCreatedSplitWorktree(
const created = await client.call<RuntimeWorktreeCreateResult>('worktree.create', {
repo: `id:${added.result.repo.id}`,
name: 'parity-setup',
branchNameOverride: 'parity-setup',
noParent: true,
activate: false,
setupDecision: 'skip'