mirror of
https://github.com/stablyai/orca.git
synced 2026-11-18 11:54:46 +00:00
Merge main after project grouping compiler repairs
This commit is contained in:
@@ -979,7 +979,6 @@
|
||||
6 test-no-wall-clock:src/main/runtime/orchestration/worker-output-archive.test.ts
|
||||
1 test-no-wall-clock:src/main/runtime/owned-session-teardown-policy.test.ts
|
||||
2 test-no-wall-clock:src/main/runtime/project-removal-structured-sessions.test.ts
|
||||
2 test-no-wall-clock:src/main/runtime/pty-shell-ownership-mirror.test.ts
|
||||
1 test-no-wall-clock:src/main/runtime/push/push-device-registration-persistence.test.ts
|
||||
1 test-no-wall-clock:src/main/runtime/push/push-registration-rpc.test.ts
|
||||
1 test-no-wall-clock:src/main/runtime/push/push-unpair-persistence.test.ts
|
||||
@@ -1062,7 +1061,7 @@
|
||||
2 test-no-wall-clock:src/main/terminal-history-fish-session.node-pty.test.ts
|
||||
2 test-no-wall-clock:src/main/terminal-history-gc-fs-call-count.test.ts
|
||||
2 test-no-wall-clock:src/main/updater-sqlite-profile-downgrade.test.ts
|
||||
6 test-no-wall-clock:src/main/updater/serve-supervisor-install-park.test.ts
|
||||
4 test-no-wall-clock:src/main/updater/serve-supervisor-install-park.test.ts
|
||||
4 test-no-wall-clock:src/main/windows-live-tree-kill.win32.test.ts
|
||||
2 test-no-wall-clock:src/main/windows/windows-host-job.win32.test.ts
|
||||
3 test-no-wall-clock:src/main/windows/windows-msys-job.win32.test.ts
|
||||
@@ -1161,7 +1160,6 @@
|
||||
1 test-no-wall-clock:src/renderer/src/store/slices/store-sleep-agent-status-retention.test.ts
|
||||
2 test-no-wall-clock:src/renderer/src/store/slices/store-sleep-exact-runtime-stop.test.ts
|
||||
7 test-no-wall-clock:src/renderer/src/store/slices/tabs-unread-and-focus.test.ts
|
||||
1 test-no-wall-clock:src/renderer/src/store/slices/terminal-helpers.test.ts
|
||||
1 test-no-wall-clock:src/renderer/src/store/slices/ui-hydration-view-layout.test.ts
|
||||
1 test-no-wall-clock:src/renderer/src/store/slices/ui-hydration-workspace-cleanup-browse.test.ts
|
||||
2 test-no-wall-clock:src/renderer/src/store/slices/workspace-cleanup-agent-stop-preflight.test.ts
|
||||
@@ -1316,7 +1314,7 @@
|
||||
2 test-timeout-needs-reason:src/main/providers/local-pty-child-process-verdict.test.ts
|
||||
3 test-timeout-needs-reason:src/main/providers/pty-repaint-wide-char-buffer.node-pty.test.ts
|
||||
2 test-timeout-needs-reason:src/main/providers/startup-line-typed-length.live-shell.test.ts
|
||||
7 test-timeout-needs-reason:src/main/pty/node-pty-master-fd-retirement.test.ts
|
||||
5 test-timeout-needs-reason:src/main/pty/node-pty-master-fd-retirement.test.ts
|
||||
2 test-timeout-needs-reason:src/main/runtime/cline-screen-readiness-transcripts.test.ts
|
||||
4 test-timeout-needs-reason:src/main/runtime/codex-header-readiness-transcripts.test.ts
|
||||
1 test-timeout-needs-reason:src/main/runtime/codex-quiet-ready-screen.test.ts
|
||||
|
||||
@@ -8667,7 +8667,7 @@
|
||||
"providers": ["local", "local-daemon", "ssh", "wsl", "remote-runtime"],
|
||||
"coveredPlatforms": ["macos"],
|
||||
"coveredProviders": ["local-daemon"],
|
||||
"coverageNotes": "Provider-independent unit tests cover persisted replay, state-boundary authority transfer, remote-runtime mirroring, rootless layouts, repeated leaf ids, metadata repair, and 12,000 nested duplicate leaves. A two-launch macOS Electron journey covers a real surviving local-daemon PTY, persisted duplicate ownership, synchronized streaming output, and tab hide/reveal. Live Linux, Windows, SSH, WSL, and remote-runtime restore journeys remain gaps.",
|
||||
"coverageNotes": "Provider-independent unit tests cover persisted replay, state-boundary authority transfer, remote-runtime mirroring, rootless layouts, repeated leaf ids, metadata repair, and 12,000 nested duplicate leaves. A two-launch macOS Electron journey covers a real surviving local-daemon PTY, persisted duplicate ownership, synchronized streaming output, and tab hide/reveal. Live Linux, Windows, SSH, WSL, and remote-runtime restore journeys remain gaps. The audit removed a mocked duplicate-replay wrapper suite. Its callback-count alarms are no longer covered here; retained ownership tests and historical Electron evidence do not establish equivalent wrapper coverage.",
|
||||
"motivatingLinks": [
|
||||
"https://github.com/stablyai/orca/issues/11757",
|
||||
"https://github.com/stablyai/orca/pull/11726"
|
||||
@@ -8675,12 +8675,11 @@
|
||||
"invariant": "Within one terminal tab, each PTY has at most one layout leaf, pane manager surface, and xterm renderer owner. Restore and remote mirroring must normalize duplicate ownership before replay while retaining active-leaf focus, scrollback, pane authority, agent metadata, and distinct sibling PTYs.",
|
||||
"oracle": "Launch Orca with a real daemon PTY running a synchronized full-screen stream, close the desktop client without killing the daemon process, seed the persisted tab layout with two leaves bound to that PTY, and relaunch. Hide the restored tab behind a sibling and reveal it, then require the stream to remain visible with exactly one manager pane, one xterm DOM node, one root leaf, one PTY binding, and one unique PTY. Unit contracts require the same one-owner result through persisted replay, store hydration, remote mirroring, rootless and repeated-leaf layouts, and deeply nested input.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-layout-duplicate-pty-replay.test.ts src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership-depth.test.ts src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership.test.ts src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts src/renderer/src/runtime/web-session-tabs-sync.test.ts --reporter=dot",
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership-depth.test.ts src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership.test.ts src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts src/renderer/src/runtime/web-session-tabs-sync.test.ts --reporter=dot",
|
||||
"pnpm exec electron-vite build --mode e2e",
|
||||
"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1"
|
||||
],
|
||||
"testFiles": [
|
||||
"src/renderer/src/components/terminal-pane/terminal-layout-duplicate-pty-replay.test.ts",
|
||||
"src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership-depth.test.ts",
|
||||
"src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership.test.ts",
|
||||
"src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts",
|
||||
@@ -8688,13 +8687,6 @@
|
||||
"tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts"
|
||||
],
|
||||
"assertionRefs": [
|
||||
{
|
||||
"file": "src/renderer/src/components/terminal-pane/terminal-layout-duplicate-pty-replay.test.ts",
|
||||
"assertions": [
|
||||
"replays one surface when restored leaves point to the same PTY",
|
||||
"reattaches one PTY when the split repeats its bound leaf id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership-depth.test.ts",
|
||||
"assertions": ["prunes deeply nested duplicate ownership without recursive stack growth"]
|
||||
@@ -8723,15 +8715,6 @@
|
||||
}
|
||||
],
|
||||
"evidenceRuns": [
|
||||
{
|
||||
"date": "2026-08-01",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-layout-duplicate-pty-replay.test.ts src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership-depth.test.ts src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership.test.ts src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts src/renderer/src/runtime/web-session-tabs-sync.test.ts --reporter=dot",
|
||||
"result": "passed",
|
||||
"durationSeconds": 1.33,
|
||||
"summary": "Five focused files passed 92 ownership, replay, hydration, depth, and remote-mirroring tests."
|
||||
},
|
||||
{
|
||||
"date": "2026-08-01",
|
||||
"runner": "local",
|
||||
@@ -8767,7 +8750,8 @@
|
||||
"Live Electron evidence currently covers macOS with a local daemon PTY only.",
|
||||
"The live journey uses a git-backed test workspace; folder-workspace restoration currently relies on the same provider-independent normalization contracts rather than a separate Electron run.",
|
||||
"The gate deterministically seeds the historical persisted-state shape; it does not depend on reproducing the unknown UI sequence that originally wrote duplicate ownership.",
|
||||
"The visual old-release evidence and the structural current-version oracle are separate runs because the current test harness did not exist in Orca 1.4.161."
|
||||
"The visual old-release evidence and the structural current-version oracle are separate runs because the current test harness did not exist in Orca 1.4.161.",
|
||||
"The audit removed a mocked duplicate-replay wrapper suite. Its callback-count alarms are no longer covered here; retained ownership tests and historical Electron evidence do not establish equivalent wrapper coverage."
|
||||
],
|
||||
"demotionRule": "Keep experimental or demote if ownership cardinality flakes, duplicate replay reaches a second renderer, active metadata or authority moves to the wrong leaf, deep normalization regresses, or a supported provider bypasses normalization."
|
||||
},
|
||||
@@ -9448,7 +9432,7 @@
|
||||
"providers": ["daemon", "runtime", "ssh", "wsl"],
|
||||
"coveredPlatforms": ["linux", "macos", "windows"],
|
||||
"coveredProviders": ["daemon", "runtime"],
|
||||
"coverageNotes": "Recorded native Windows evidence covers the v21/v22/v23/v24/v25 named-pipe matrix. The deterministic daemon harness covers capable and legacy paired-runtime request shapes against live v25/v26 PTYs in separate worktrees, plus an unrelated control. Host/renderer tests cover old servers, missing liveness, stale publications, reused claims, split parents, explicit user intent, cross-profile isolation, remote runtime clients, SSH-provider routing, and WSL boundaries. A headed host paired to a separate live client, headless serve parity, Linux, SSH, and WSL remain explicit gaps.",
|
||||
"coverageNotes": "Recorded native Windows evidence covers the v21/v22/v23/v24/v25 named-pipe matrix. The deterministic daemon harness covers capable and legacy paired-runtime request shapes against live v25/v26 PTYs in separate worktrees, plus an unrelated control. Host/renderer tests cover old servers, missing liveness, stale publications, reused claims, split parents, explicit user intent, cross-profile isolation, remote runtime clients, SSH-provider routing, and WSL boundaries. A headed host paired to a separate live client, headless serve parity, Linux, SSH, and WSL remain explicit gaps. The audit removed private-router tests of mocked kill results and log fields. Their isolated success/failure attribution and pending-spawn tolerance alarms are no longer registered here; live lifecycle evidence does not establish equivalent log coverage.",
|
||||
"motivatingLinks": [
|
||||
"https://github.com/stablyai/orca/issues/9749",
|
||||
"https://github.com/stablyai/orca/issues/9949",
|
||||
@@ -9459,12 +9443,11 @@
|
||||
"invariant": "Reconnect, replay, or lifecycle observations from a viewer that negotiated explicit close intent must never kill a live PTY. A capable reasonless close must keep and republish; a legacy paired viewer must retain current-main behavior because its intentional close and cleanup echo are wire-identical. Lifecycle close requires the exact observed publication, terminal, environment, and authoritative liveness, never signals a process, and leaves renderer-owned or partial-split retirement to its owner. Legacy daemon hello and warm reattachment remain non-destructive.",
|
||||
"oracle": "Start isolated v25 and v26 daemon generations with one capable-viewer PTY and one legacy-viewer PTY per generation in four target worktrees plus an unaddressed control PTY in a fifth worktree. Route them through the production desktop scanner, runtime, RPC dispatcher, renderer-close relay, and daemon router. First issue sequential reasonless closes from an authenticated capable connection and require refusal, snapshot republish, zero shutdown calls, exact process survival, and post-close I/O. Then issue the byte-identical requests without the negotiated capability and require current-main behavior: two ordered immediate shutdowns, session-killed events, and exact root/descendant death, while capable and control PTYs survive. An observer lists all targets before, between, and after while issuing zero closes. Unit contracts also require in-process reasonless refusal, legacy runtime/mobile compatibility, explicit user closes, encrypted client-auth advertisement, and old-server lifecycle calls never to fall back.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/daemon-server-kill-attribution.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/remote-runtime-request-connection.integration.test.ts src/main/runtime/rpc/runtime-close-attribution-topology.test.ts src/main/runtime/rpc/methods/session-tabs.test.ts src/main/runtime/rpc/e2ee-channel.test.ts src/main/runtime/rpc/e2ee-channel-v2.test.ts src/main/runtime/rpc/mobile-socket-wiring.test.ts src/main/runtime/rpc/runtime-client-capabilities.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/requests/remote-runtime-request-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/cli/runtime/websocket-transport.test.ts src/renderer/src/web/web-runtime-client.test.ts src/renderer/src/runtime/web-runtime-session.test.ts src/renderer/src/runtime/web-session-close-intent.test.ts src/renderer/src/runtime/web-session-tabs-sync.test.ts src/renderer/src/components/terminal/terminal-tab-actions.test.ts src/renderer/src/components/terminal/terminal-close-incarnation.test.ts src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts",
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/remote-runtime-request-connection.integration.test.ts src/main/runtime/rpc/runtime-close-attribution-topology.test.ts src/main/runtime/rpc/methods/session-tabs.test.ts src/main/runtime/rpc/e2ee-channel.test.ts src/main/runtime/rpc/e2ee-channel-v2.test.ts src/main/runtime/rpc/mobile-socket-wiring.test.ts src/main/runtime/rpc/runtime-client-capabilities.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/requests/remote-runtime-request-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/cli/runtime/websocket-transport.test.ts src/renderer/src/web/web-runtime-client.test.ts src/renderer/src/runtime/web-runtime-session.test.ts src/renderer/src/runtime/web-session-close-intent.test.ts src/renderer/src/runtime/web-session-tabs-sync.test.ts src/renderer/src/components/terminal/terminal-tab-actions.test.ts src/renderer/src/components/terminal/terminal-close-incarnation.test.ts src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts",
|
||||
"pnpm exec playwright test tests/e2e/daemon-generation-reconnect-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
|
||||
"pnpm exec playwright test tests/e2e/daemon-generation-legacy-close-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1"
|
||||
],
|
||||
"testFiles": [
|
||||
"src/main/daemon/daemon-server-kill-attribution.test.ts",
|
||||
"src/main/runtime/orca-runtime.test.ts",
|
||||
"src/main/runtime/remote-runtime-request-connection.integration.test.ts",
|
||||
"src/main/runtime/rpc/runtime-close-attribution-topology.test.ts",
|
||||
@@ -9488,12 +9471,6 @@
|
||||
"tests/e2e/daemon-generation-legacy-close-safety.spec.ts"
|
||||
],
|
||||
"assertionRefs": [
|
||||
{
|
||||
"file": "src/main/daemon/daemon-server-kill-attribution.test.ts",
|
||||
"assertions": [
|
||||
"successful and failed daemon kill requests retain the authenticated control-client identity without claiming a failed kill succeeded"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "src/main/runtime/rpc/runtime-close-attribution-topology.test.ts",
|
||||
"assertions": [
|
||||
@@ -9656,7 +9633,8 @@
|
||||
"Headless orca serve parity, live Linux, Linux SSH relay, and Windows WSL reconnect are not exercised; Docker SSH would cover only the SSH provider and cannot substitute for paired Orca-server evidence.",
|
||||
"A topology containing any pre-contract paired desktop viewer remains vulnerable to that viewer's stale reasonless close storm; preserving its intentional-close behavior makes this unavoidable until the viewer upgrades.",
|
||||
"Cross-profile daemon inventory and generation handoff/retirement remain the separate #9138/#9229 design.",
|
||||
"A dead split leaf stays with its authoritative owner rather than being remotely pruned."
|
||||
"A dead split leaf stays with its authoritative owner rather than being remotely pruned.",
|
||||
"The audit removed private-router tests of mocked kill results and log fields. Their isolated success/failure attribution and pending-spawn tolerance alarms are no longer registered here; live lifecycle evidence does not establish equivalent log coverage."
|
||||
],
|
||||
"demotionRule": "Keep experimental or quarantine if reconnect emits session-killed for a live canary, an exact root/descendant dies, an old server receives fallback destructive close, cleanup leaks a fixture process/pipe, or the gate flakes without a proven harness defect."
|
||||
},
|
||||
@@ -17372,7 +17350,7 @@
|
||||
"providers": ["remote-runtime", "ssh", "local", "daemon"],
|
||||
"coveredPlatforms": ["macos"],
|
||||
"coveredProviders": ["remote-runtime"],
|
||||
"coverageNotes": "Local macOS evidence covers runtime-RPC stream budgets, paired-renderer parse/discard credit, and negotiated host-side suppression for hidden paired desktop panes. Deferred credit is shared by local and remote transports, batches ACKs at 192 KiB or 4 ms, grows per-stream windows from 512 KiB to 2 MiB and aggregate windows from 2 MiB to 8 MiB, bounds queued output to 256 KiB per stream, and caps each multiplex connection at 32 active or pending streams for an 8 MiB aggregate pending-output ceiling. Deterministic tests cover replay ordering, stale generations, malformed frames, hidden panes, queue eviction, disposal, send/recovery failure, repeated pending-slot replacement, reconnect, mixed-version pause negotiation, and round-robin fairness. The opt-in benchmark models 1/20/100 ms RTT and 1/4/8 viewers, throughput, window use, completion spread and protocol-frame counts. It measures model scheduler elapsed time separately from actual @xterm/headless parser CPU/retained heap; modeled credit and ACK results do not qualify production credit enforcement. Live Android restore evidence, browser/WebGL parser measurements, and legacy JSON subscribe parity remain required.",
|
||||
"coverageNotes": "Local macOS evidence covers runtime-RPC stream budgets, paired-renderer parse/discard credit, and negotiated host-side suppression for hidden paired desktop panes. Deferred credit is shared by local and remote transports, batches ACKs at 192 KiB or 4 ms, grows per-stream windows from 512 KiB to 2 MiB and aggregate windows from 2 MiB to 8 MiB, bounds queued output to 256 KiB per stream, and caps each multiplex connection at 32 active or pending streams for an 8 MiB aggregate pending-output ceiling. Deterministic tests cover replay ordering, stale generations, malformed frames, hidden panes, queue eviction, disposal, send/recovery failure, repeated pending-slot replacement, reconnect, mixed-version pause negotiation, and round-robin fairness. The opt-in benchmark models 1/20/100 ms RTT and 1/4/8 viewers, throughput, window use, completion spread and protocol-frame counts. It measures model scheduler elapsed time separately from actual @xterm/headless parser CPU/retained heap; modeled credit and ACK results do not qualify production credit enforcement. Live Android restore evidence, browser/WebGL parser measurements, and legacy JSON subscribe parity remain required. The audit removed the PTY ACK wrapper suite, which replayed credit arithmetic with mocked IPC. Its isolated wrapper alarms are no longer registered here; generic credit and runtime stream tests do not establish equivalent PTY integration coverage.",
|
||||
"motivatingLinks": [
|
||||
"https://github.com/stablyai/orca/pull/6951",
|
||||
"https://github.com/stablyai/orca/pull/6955",
|
||||
@@ -17383,7 +17361,7 @@
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts --maxWorkers=1",
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/terminal-subscribe-buffer.test.ts src/main/runtime/rpc/terminal-output-batching.test.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts",
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/terminal-subscribe-buffer.test.ts src/main/runtime/rpc/terminal-output-batching.test.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts src/renderer/src/components/terminal-pane/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/terminal-pty-ack-gate.test.ts src/renderer/src/lib/pane-manager/terminal-delivery-credit.test.ts src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts src/renderer/src/runtime/runtime-terminal-stream.test.ts --maxWorkers=1",
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/terminal-subscribe-buffer.test.ts src/main/runtime/rpc/terminal-output-batching.test.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts src/renderer/src/components/terminal-pane/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/lib/pane-manager/terminal-delivery-credit.test.ts src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts src/renderer/src/runtime/runtime-terminal-stream.test.ts --maxWorkers=1",
|
||||
"ORCA_TERMINAL_PERF_BENCH=1 pnpm exec vitest run --config config/vitest.config.ts --disableConsoleIntercept src/main/runtime/rpc/terminal-multiplex-flow-control.bench.test.ts",
|
||||
"pnpm --dir mobile exec vitest run --root .. mobile/src/session/native-chat/mobile-native-chat-terminal-stream.test.ts",
|
||||
"pnpm --dir mobile exec vitest run --root .. mobile/src/session/native-chat/use-mobile-native-chat-terminal-stream.test.ts"
|
||||
@@ -17399,7 +17377,6 @@
|
||||
"src/main/runtime/rpc/terminal-multiplex-flow-control.bench.test.ts",
|
||||
"src/renderer/src/components/terminal-pane/pty-connection-hidden-replay.test.ts",
|
||||
"src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts",
|
||||
"src/renderer/src/components/terminal-pane/terminal-pty-ack-gate.test.ts",
|
||||
"src/renderer/src/lib/pane-manager/terminal-delivery-credit.test.ts",
|
||||
"src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts",
|
||||
"src/renderer/src/runtime/runtime-terminal-stream.test.ts",
|
||||
@@ -17570,7 +17547,8 @@
|
||||
"knownGaps": [
|
||||
"The pure mobile decision gate does not yet prove live Android WebView scrollback restore after a chat toggle.",
|
||||
"Legacy JSON subscribe parity is undecided.",
|
||||
"The parser measurement uses @xterm/headless; browser renderer/WebGL CPU, GPU, and allocation behavior still need packaged-app performance evidence."
|
||||
"The parser measurement uses @xterm/headless; browser renderer/WebGL CPU, GPU, and allocation behavior still need packaged-app performance evidence.",
|
||||
"The audit removed the PTY ACK wrapper suite, which replayed credit arithmetic with mocked IPC. Its isolated wrapper alarms are no longer registered here; generic credit and runtime stream tests do not establish equivalent PTY integration coverage."
|
||||
],
|
||||
"demotionRule": "Cannot promote while a supported stream path has uncapped snapshot or live-output buffering."
|
||||
},
|
||||
|
||||
@@ -2130,7 +2130,6 @@
|
||||
"src/main/daemon/daemon-server-attach-only.test.ts": 477,
|
||||
"src/main/daemon/daemon-server-attachment-lifecycle.test.ts": 676,
|
||||
"src/main/daemon/daemon-server-error-handling.test.ts": 822,
|
||||
"src/main/daemon/daemon-server-kill-attribution.test.ts": 902,
|
||||
"src/main/daemon/daemon-server.test.ts": 1218,
|
||||
"src/main/daemon/daemon-session-owner-resolution.test.ts": 106,
|
||||
"src/main/daemon/daemon-session-scrollback-window.test.ts": 513,
|
||||
@@ -2308,7 +2307,6 @@
|
||||
"src/main/emulator/android/uiautomator-tree.test.ts": 77,
|
||||
"src/main/emulator/backends/android-emulator-backend.test.ts": 230,
|
||||
"src/main/emulator/backends/ios-emulator-backend.test.ts": 167,
|
||||
"src/main/emulator/emulator-availability.test.ts": 68,
|
||||
"src/main/emulator/emulator-bridge.test.ts": 397,
|
||||
"src/main/emulator/emulator-gesture-sender.test.ts": 174,
|
||||
"src/main/emulator/emulator-session-registry.test.ts": 50,
|
||||
@@ -3346,7 +3344,6 @@
|
||||
"src/main/managed-server/activation/orcad-activation-crash-recovery.test.ts": 430,
|
||||
"src/main/managed-server/activation/orcad-activation-fence-generation.test.ts": 608,
|
||||
"src/main/managed-server/activation/orcad-activation-fence-hold.test.ts": 345,
|
||||
"src/main/managed-server/activation/orcad-activation-gate.test.ts": 65,
|
||||
"src/main/managed-server/activation/orcad-activation-record.test.ts": 131,
|
||||
"src/main/managed-server/activation/orcad-activation-transaction.test.ts": 258,
|
||||
"src/main/managed-server/host-state/orcad-machine-home.test.ts": 1699,
|
||||
@@ -3955,7 +3952,6 @@
|
||||
"src/main/orcad/orcad-compile-cache.test.ts": 60,
|
||||
"src/main/orcad/orcad-cross-runtime-daemon-adoption.integration.test.ts": 484,
|
||||
"src/main/orcad/orcad-daemon-retirement.test.ts": 202,
|
||||
"src/main/orcad/orcad-daemon-supervision.test.ts": 107,
|
||||
"src/main/orcad/orcad-daemon-teardown-linux.test.ts": 787,
|
||||
"src/main/orcad/orcad-daemon-teardown-pid-reuse.test.ts": 595,
|
||||
"src/main/orcad/orcad-data-root-locality.test.ts": 51,
|
||||
@@ -4598,7 +4594,6 @@
|
||||
"src/main/repo-icon-autodetect.test.ts": 693,
|
||||
"src/main/repo-icon-file-detection.test.ts": 485,
|
||||
"src/main/repo-icon-source-href.test.ts": 75,
|
||||
"src/main/repo-maintenance-idle-gate.test.ts": 125,
|
||||
"src/main/repo-worktrees.test.ts": 410,
|
||||
"src/main/ripgrep/bundled-ripgrep-path.test.ts": 78,
|
||||
"src/main/ripgrep/bundled-ripgrep-real.test.ts": 172,
|
||||
@@ -4858,7 +4853,6 @@
|
||||
"src/main/runtime/mobile-session-tab-close-refusal-message.test.ts": 43,
|
||||
"src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts": 59,
|
||||
"src/main/runtime/mobile-session-tabs-churn-coalescing.test.ts": 2207,
|
||||
"src/main/runtime/mobile-session-tabs-notify-coalescer.test.ts": 53,
|
||||
"src/main/runtime/mobile-session-terminal-persistence-retirement.test.ts": 218,
|
||||
"src/main/runtime/mobile-session-terminal-retirement-proof.test.ts": 43,
|
||||
"src/main/runtime/mobile-session-terminal-retirement.test.ts": 155,
|
||||
@@ -5181,7 +5175,6 @@
|
||||
"src/main/runtime/rpc/methods/agent-launch-settings-work.test.ts": 5277,
|
||||
"src/main/runtime/rpc/methods/agent-launch-structured-prompt.test.ts": 122,
|
||||
"src/main/runtime/rpc/methods/agent-launch-terminal-identity.test.ts": 1277,
|
||||
"src/main/runtime/rpc/methods/agent-launch-terminal-preferences.test.ts": 969,
|
||||
"src/main/runtime/rpc/methods/agent-launch-terminal-prompt-writer.test.ts": 10669,
|
||||
"src/main/runtime/rpc/methods/agent-launch-terminal-prompt.test.ts": 522,
|
||||
"src/main/runtime/rpc/methods/agent-launch.test.ts": 1343,
|
||||
@@ -5325,7 +5318,6 @@
|
||||
"src/main/runtime/rpc/methods/orchestration/worker/worker-start-prompt-budget.test.ts": 111,
|
||||
"src/main/runtime/rpc/methods/orchestration/worker/worker-start-prompt-contract.test.ts": 3293,
|
||||
"src/main/runtime/rpc/methods/orchestration/worker/worker-start-readiness-settlement.test.ts": 541,
|
||||
"src/main/runtime/rpc/methods/orchestration/worker/worker-start-turn-observation.test.ts": 43,
|
||||
"src/main/runtime/rpc/methods/orchestration/worker/worker-stop-exit-race.test.ts": 3668,
|
||||
"src/main/runtime/rpc/methods/orchestration/worker/worker-stop-liveness-verdict.test.ts": 3343,
|
||||
"src/main/runtime/rpc/methods/orchestration/worker/worker-terminal-custody-at-creation.test.ts": 3239,
|
||||
@@ -6119,7 +6111,6 @@
|
||||
"src/main/ssh/connection/ssh-connection-system-transport.test.ts": 276,
|
||||
"src/main/ssh/connection/ssh-connection-wake-retry.test.ts": 316,
|
||||
"src/main/ssh/connection/ssh-connection.test.ts": 1650,
|
||||
"src/main/ssh/hostile-host-test-support/ssh-hostile-host-cells.test.ts": 74,
|
||||
"src/main/ssh/hostile-host-test-support/ssh-hostile-hosts.docker.test.ts": 575,
|
||||
"src/main/ssh/legacy-relay/legacy-relay-bridge-relay-restart.test.ts": 70,
|
||||
"src/main/ssh/legacy-relay/legacy-relay-bridge-restart-stop.test.ts": 3036,
|
||||
@@ -6327,7 +6318,6 @@
|
||||
"src/main/startup/profile-state-recovery-preflight.test.ts": 603,
|
||||
"src/main/startup/profile-state-save-delay.test.ts": 39,
|
||||
"src/main/startup/profile-state-write-failure.test.ts": 425,
|
||||
"src/main/startup/renderer-heap-headroom.test.ts": 74,
|
||||
"src/main/startup/run-electron-vite-dev-web.test.ts": 697,
|
||||
"src/main/startup/run-electron-vite-dev.test.ts": 899,
|
||||
"src/main/startup/select-linux-keyring-backend.test.ts": 63,
|
||||
@@ -6393,7 +6383,6 @@
|
||||
"src/main/text-generation/commit-message-text-generation-cancellation.test.ts": 914,
|
||||
"src/main/text-generation/commit-message-text-generation-failure-sanitization.test.ts": 584,
|
||||
"src/main/text-generation/commit-message-text-generation-generated-output.test.ts": 445,
|
||||
"src/main/text-generation/commit-message-text-generation-linked-issue.test.ts": 475,
|
||||
"src/main/text-generation/commit-message-text-generation-local-subprocess.test.ts": 302,
|
||||
"src/main/text-generation/commit-message-text-generation-model-discovery.test.ts": 417,
|
||||
"src/main/text-generation/commit-message-text-generation-regression.test.ts": 391,
|
||||
@@ -6574,7 +6563,6 @@
|
||||
"src/main/worktree-create-base.test.ts": 41,
|
||||
"src/main/worktree-create-candidates.test.ts": 54,
|
||||
"src/main/worktree-create-concurrency.test.ts": 44,
|
||||
"src/main/worktree-create-execution-host-route.test.ts": 495,
|
||||
"src/main/worktree-create-in-flight.test.ts": 175,
|
||||
"src/main/worktree-create-preparation-activity.test.ts": 42,
|
||||
"src/main/worktree-create-preparation-cancellation.test.ts": 613,
|
||||
@@ -6597,7 +6585,6 @@
|
||||
"src/main/worktree-prunable-git-file.test.ts": 42,
|
||||
"src/main/worktree-removal-authority.test.ts": 142,
|
||||
"src/main/worktree-removal-close-records.test.ts": 1302,
|
||||
"src/main/worktree-removal-execution-host-route.test.ts": 413,
|
||||
"src/main/worktree-removal-home-guard.test.ts": 85,
|
||||
"src/main/worktree-removal-repo-owner.test.ts": 42,
|
||||
"src/main/worktree-removal-safety.test.ts": 153,
|
||||
@@ -7015,7 +7002,6 @@
|
||||
"src/renderer/src/components/browser-pane/navigate/browser-load-failure-overlay.test.tsx": 549,
|
||||
"src/renderer/src/components/browser-pane/navigate/browser-notices.test.ts": 173,
|
||||
"src/renderer/src/components/browser-pane/navigate/browser-page-download-activity.test.ts": 41,
|
||||
"src/renderer/src/components/browser-pane/navigate/browser-reload-action.test.ts": 52,
|
||||
"src/renderer/src/components/browser-pane/navigate/browser-webview-load-failure.test.ts": 105,
|
||||
"src/renderer/src/components/browser-pane/navigate/chromium-error-page-poll-visibility.test.ts": 2172,
|
||||
"src/renderer/src/components/browser-pane/navigate/chromium-error-page-polling.test.ts": 25,
|
||||
@@ -7091,7 +7077,6 @@
|
||||
"src/renderer/src/components/dashboard-popout/preview-grid-claim.test.ts": 322,
|
||||
"src/renderer/src/components/dashboard-popout/preview-terminal-box-fit-lifecycle.test.ts": 294,
|
||||
"src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts": 333,
|
||||
"src/renderer/src/components/dashboard-popout/preview-terminal-options.test.ts": 170,
|
||||
"src/renderer/src/components/dashboard-popout/preview-terminal-right-click-paste.test.ts": 1760,
|
||||
"src/renderer/src/components/dashboard-popout/preview-terminal-shortcuts.test.ts": 178,
|
||||
"src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts": 38,
|
||||
@@ -7171,7 +7156,6 @@
|
||||
"src/renderer/src/components/editor/IpynbKernelToolbar.test.tsx": 581,
|
||||
"src/renderer/src/components/editor/IpynbRendering.test.tsx": 1560,
|
||||
"src/renderer/src/components/editor/LargeDiffLoadPrompt.test.tsx": 286,
|
||||
"src/renderer/src/components/editor/MarkdownPreview.image-access.test.tsx": 753,
|
||||
"src/renderer/src/components/editor/MarkdownPreview.link-routing.interaction.test.tsx": 828,
|
||||
"src/renderer/src/components/editor/MarkdownPreview.test.ts": 1141,
|
||||
"src/renderer/src/components/editor/MarkdownPreview.toc-visibility-gate.test.tsx": 933,
|
||||
@@ -7272,7 +7256,6 @@
|
||||
"src/renderer/src/components/editor/editor-header.test.ts": 57,
|
||||
"src/renderer/src/components/editor/editor-labels.test.ts": 46,
|
||||
"src/renderer/src/components/editor/editor-model-host-isolation.test.ts": 5854,
|
||||
"src/renderer/src/components/editor/editor-model-owner.test.ts": 316,
|
||||
"src/renderer/src/components/editor/editor-model-uri-labels.test.ts": 1029,
|
||||
"src/renderer/src/components/editor/editor-model-uri-language-service.test.ts": 2417,
|
||||
"src/renderer/src/components/editor/editor-model-uri-parity.test.ts": 154,
|
||||
@@ -7363,7 +7346,6 @@
|
||||
"src/renderer/src/components/editor/monaco-content-sync.undo-history.test.ts": 996,
|
||||
"src/renderer/src/components/editor/monaco-context-menu-paste.test.ts": 230,
|
||||
"src/renderer/src/components/editor/monaco-cursor-line-lifetime.test.ts": 1210,
|
||||
"src/renderer/src/components/editor/monaco-find-widget.test.ts": 147,
|
||||
"src/renderer/src/components/editor/monaco-large-text-paste.test.ts": 209,
|
||||
"src/renderer/src/components/editor/monaco-markdown-doc-completions-retention.test.ts": 66,
|
||||
"src/renderer/src/components/editor/monaco-markdown-doc-link-decorations.offset-scan.test.ts": 167,
|
||||
@@ -7587,7 +7569,6 @@
|
||||
"src/renderer/src/components/jira-prompt-templates.test.ts": 106,
|
||||
"src/renderer/src/components/jira-self-user.test.ts": 44,
|
||||
"src/renderer/src/components/landing-preflight-dismissal.test.ts": 104,
|
||||
"src/renderer/src/components/landing-preflight-issues.test.ts": 134,
|
||||
"src/renderer/src/components/landing-preflight-runtime-boundary.test.ts": 1576,
|
||||
"src/renderer/src/components/landing-preflight-unverifiable-host.test.tsx": 1436,
|
||||
"src/renderer/src/components/linear-api-key-dialog-state.test.ts": 53,
|
||||
@@ -8433,7 +8414,6 @@
|
||||
"src/renderer/src/components/settings/browser-session-host-selection.test.ts": 43,
|
||||
"src/renderer/src/components/settings/bundled-skill-setup-result-copy.test.ts": 304,
|
||||
"src/renderer/src/components/settings/chat-naming-persistence.test.tsx": 3654,
|
||||
"src/renderer/src/components/settings/cli-install-failure.test.ts": 34,
|
||||
"src/renderer/src/components/settings/codex-config-sync-warning.test.ts": 34,
|
||||
"src/renderer/src/components/settings/developer-permissions-search.test.ts": 178,
|
||||
"src/renderer/src/components/settings/general-editor-search.test.ts": 136,
|
||||
@@ -8454,7 +8434,6 @@
|
||||
"src/renderer/src/components/settings/repository/execution/RepositoryHooksSection.test.ts": 715,
|
||||
"src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.settings-entry.test.tsx": 1786,
|
||||
"src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.test.tsx": 1674,
|
||||
"src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.workspace-window.test.tsx": 1584,
|
||||
"src/renderer/src/components/settings/repository/execution/RepositoryWorktreeDefaultsSection.test.tsx": 577,
|
||||
"src/renderer/src/components/settings/repository/execution/repository-hook-settings-draft.test.ts": 368,
|
||||
"src/renderer/src/components/settings/repository/execution/repository-host-setup-options.test.ts": 151,
|
||||
@@ -8817,7 +8796,6 @@
|
||||
"src/renderer/src/components/sidebar/worktree-manual-order.test.ts": 237,
|
||||
"src/renderer/src/components/sidebar/worktree-name-suggestions.test.ts": 142,
|
||||
"src/renderer/src/components/sidebar/worktree-parent-eligibility.test.ts": 36,
|
||||
"src/renderer/src/components/sidebar/worktree-review-helpers.test.tsx": 92,
|
||||
"src/renderer/src/components/sidebar/worktree-scroll-to-current-button.test.ts": 51,
|
||||
"src/renderer/src/components/sidebar/worktree-sidebar-drag-autoscroll.test.ts": 63,
|
||||
"src/renderer/src/components/sidebar/worktree-sidebar-drag-geometry.test.ts": 79,
|
||||
@@ -9055,7 +9033,6 @@
|
||||
"src/renderer/src/components/task-page-jira-grouping.test.ts": 1486,
|
||||
"src/renderer/src/components/task-page/jira/task-page-jira-linked-issues.test.ts": 54,
|
||||
"src/renderer/src/components/task-page/jira/task-page-jira-load-state.test.ts": 48,
|
||||
"src/renderer/src/components/task-page/jira/task-page-jira-project-selection.test.ts": 28,
|
||||
"src/renderer/src/components/task-page/jira/task-page-jira-quick-copy.test.tsx": 2171,
|
||||
"src/renderer/src/components/task-page/jira/task-page-jira-saved-filter-application.test.tsx": 1838,
|
||||
"src/renderer/src/components/task-page-jira-saved-filter-load-failure.test.tsx": 2974,
|
||||
@@ -9088,7 +9065,6 @@
|
||||
"src/renderer/src/components/task-page/jira/IssueUserField.test.tsx": 2183,
|
||||
"src/renderer/src/components/task-page/linear/task-page-linear-in-orca-issues.test.ts": 98,
|
||||
"src/renderer/src/components/task-page/linear/task-page-linear-issue-grouping.test.ts": 1441,
|
||||
"src/renderer/src/components/task-page/linear/task-page-linear-issue-request.test.ts": 57,
|
||||
"src/renderer/src/components/task-page/linear/task-page-linear-team-selection.test.ts": 46,
|
||||
"src/renderer/src/components/task-page/task-page-default-repo-selection.test.ts": 42,
|
||||
"src/renderer/src/components/task-page/task-page-initial-selection-scaling.test.tsx": 1703,
|
||||
@@ -9487,7 +9463,6 @@
|
||||
"src/renderer/src/components/terminal-pane/terminal-keyboard-protocol-pane-agent.test.ts": 37,
|
||||
"src/renderer/src/components/terminal-pane/terminal-keyboard-search-dispatch.test.ts": 893,
|
||||
"src/renderer/src/components/terminal-pane/terminal-kitty-csi-u-encoding.test.ts": 59,
|
||||
"src/renderer/src/components/terminal-pane/terminal-layout-duplicate-pty-replay.test.ts": 39,
|
||||
"src/renderer/src/components/terminal-pane/terminal-layout-leaf-detach.test.ts": 37,
|
||||
"src/renderer/src/components/terminal-pane/terminal-layout-leaf-ids.test.ts": 44,
|
||||
"src/renderer/src/components/terminal-pane/terminal-layout-overlay-focus.test.tsx": 206,
|
||||
@@ -9534,7 +9509,6 @@
|
||||
"src/renderer/src/components/terminal-pane/terminal-pane-element-file-drop.test.tsx": 1853,
|
||||
"src/renderer/src/components/terminal-pane/terminal-pane-frame-reconciliation.test.ts": 387,
|
||||
"src/renderer/src/components/terminal-pane/terminal-pane-host-state-memo.test.ts": 2151,
|
||||
"src/renderer/src/components/terminal-pane/terminal-pane-host-state.test.ts": 1272,
|
||||
"src/renderer/src/components/terminal-pane/terminal-pane-layout-owner-commands.test.ts": 222,
|
||||
"src/renderer/src/components/terminal-pane/terminal-pane-layout-owner-gestures.test.ts": 43,
|
||||
"src/renderer/src/components/terminal-pane/terminal-pane-local-windows-conpty.test.ts": 1431,
|
||||
@@ -9577,7 +9551,6 @@
|
||||
"src/renderer/src/components/terminal-pane/terminal-path-exists-cache.test.ts": 30,
|
||||
"src/renderer/src/components/terminal-pane/terminal-process-exit-restart.test.ts": 42,
|
||||
"src/renderer/src/components/terminal-pane/terminal-programmatic-text-paste.test.ts": 272,
|
||||
"src/renderer/src/components/terminal-pane/terminal-pty-ack-gate.test.ts": 159,
|
||||
"src/renderer/src/components/terminal-pane/terminal-quick-command-dispatch.test.ts": 59,
|
||||
"src/renderer/src/components/terminal-pane/terminal-remote-runtime-recovery-ui-state.test.ts": 22,
|
||||
"src/renderer/src/components/terminal-pane/terminal-render-desync-evidence-persistence.test.ts": 52,
|
||||
@@ -9742,7 +9715,6 @@
|
||||
"src/renderer/src/components/workspace-surface-projection.test.ts": 48,
|
||||
"src/renderer/src/components/worktree-jump-palette-browser-navigation.test.tsx": 2772,
|
||||
"src/renderer/src/components/worktree-jump-palette-interleaved-sections.test.tsx": 2023,
|
||||
"src/renderer/src/components/worktree-jump-palette-primitives.test.tsx": 384,
|
||||
"src/renderer/src/components/worktree-jump-palette-quick-action-availability.test.tsx": 1441,
|
||||
"src/renderer/src/components/worktree-jump-palette-recent-inclusion.test.ts": 93,
|
||||
"src/renderer/src/components/worktree-jump-palette-sleeping-filter.test.ts": 36,
|
||||
@@ -11017,7 +10989,6 @@
|
||||
"src/renderer/src/store/slices/browser-session-host-selection.test.ts": 670,
|
||||
"src/renderer/src/store/slices/browser-session-profiles.test.ts": 894,
|
||||
"src/renderer/src/store/slices/browser-tab-creation-placement.test.ts": 1372,
|
||||
"src/renderer/src/store/slices/browser-webview-cleanup.test.ts": 57,
|
||||
"src/renderer/src/store/slices/browser-workspace-doc-location.test.ts": 1464,
|
||||
"src/renderer/src/store/slices/browser-workspace-host-ownership.test.ts": 1531,
|
||||
"src/renderer/src/store/slices/browser.test.ts": 1679,
|
||||
@@ -11267,7 +11238,6 @@
|
||||
"src/renderer/src/store/slices/tabs/tabs-reconciliation-batch-identity.test.ts": 1309,
|
||||
"src/renderer/src/store/slices/tabs/tabs-reconciliation-empty-groups.test.ts": 1204,
|
||||
"src/renderer/src/store/slices/tabs/tabs-root-group.test.ts": 1263,
|
||||
"src/renderer/src/store/slices/terminal-helpers.test.ts": 68,
|
||||
"src/renderer/src/store/slices/terminal-input-activity-store-write.test.ts": 1443,
|
||||
"src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts": 1313,
|
||||
"src/renderer/src/store/slices/terminal-orphan-helpers.test.ts": 170,
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { globSync, readFileSync } from 'node:fs'
|
||||
import { dirname, posix, resolve } from 'node:path'
|
||||
import { expect, it } from 'vitest'
|
||||
|
||||
const root = resolve(import.meta.dirname, '../..')
|
||||
const references = (file) =>
|
||||
JSON.parse(readFileSync(resolve(root, file), 'utf8')).references.map(({ path }) =>
|
||||
posix.join(posix.dirname(file), path)
|
||||
)
|
||||
|
||||
// Unit tests transform with this pinned solution, so a project missing from it loses its compiler options.
|
||||
it('lists every project tsconfig auto-discovery would find for unit-test sources', () => {
|
||||
const nested = globSync('**/tsconfig.json', {
|
||||
cwd: root,
|
||||
exclude: ['**/node_modules/**', 'mobile/**', 'docs/**']
|
||||
})
|
||||
.map((file) => file.replaceAll('\\', '/'))
|
||||
.filter((file) => dirname(file) !== '.')
|
||||
expect(references('config/tsconfig.vitest-transform.json').sort()).toEqual(
|
||||
[...nested, ...references('tsconfig.json')].sort()
|
||||
)
|
||||
})
|
||||
@@ -35,7 +35,7 @@ import {
|
||||
type MobileNativeChatPendingItem
|
||||
} from './mobile-native-chat-render-data'
|
||||
import { useMobileNativeChatRowKeys } from './native-chat/transcript/mobile-native-chat-row-keys'
|
||||
import { useMobileNativeChatPinchGesture } from './use-mobile-native-chat-pinch-gesture'
|
||||
import { useMobileNativeChatPinchGesture } from './native-chat/transcript/use-mobile-native-chat-pinch-gesture'
|
||||
import { useMobileNativeChatTailFollow } from './use-mobile-native-chat-tail-follow'
|
||||
import { useMobileNativeChatTurnDisclosure } from './native-chat/transcript/use-mobile-native-chat-turn-disclosure'
|
||||
import {
|
||||
|
||||
+1
-4
@@ -1,10 +1,7 @@
|
||||
import { createElement } from 'react'
|
||||
import { act, create } from 'react-test-renderer'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
FONT_SCALE_STEP,
|
||||
quantizeFontScale
|
||||
} from './native-chat/transcript/mobile-native-chat-message-text'
|
||||
import { FONT_SCALE_STEP, quantizeFontScale } from './mobile-native-chat-message-text'
|
||||
|
||||
const handlers: { start?: () => void; update?: (e: { scale: number }) => void } = {}
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import { useMemo, useRef, useState } from 'react'
|
||||
import { Gesture } from 'react-native-gesture-handler'
|
||||
import type { ComposedGesture } from 'react-native-gesture-handler'
|
||||
import { quantizeFontScale } from './native-chat/transcript/mobile-native-chat-message-text'
|
||||
import { quantizeFontScale } from './mobile-native-chat-message-text'
|
||||
|
||||
// Anchor each pinch on the committed scale so successive gestures compound.
|
||||
export function useMobileNativeChatPinchGesture(): {
|
||||
@@ -20,20 +20,6 @@ const pinnedIdentity = {
|
||||
}
|
||||
|
||||
describe('browser route partition identity', () => {
|
||||
it('derives a stable opaque cross-platform partition and binding fingerprint', () => {
|
||||
const first = deriveBrowserRoutePartition(identity)
|
||||
const second = deriveBrowserRoutePartition({ ...identity })
|
||||
|
||||
expect(second).toEqual(first)
|
||||
expect(first.partition).toMatch(/^persist:orca-browser-v1-[a-f0-9]{64}$/)
|
||||
expect(first.bindingFingerprint).toMatch(/^[a-f0-9]{64}$/)
|
||||
expect(first.partition.slice('persist:'.length)).toMatch(/^[a-z0-9-]+$/)
|
||||
for (const rawIdentity of Object.values(identity)) {
|
||||
expect(first.partition).not.toContain(rawIdentity)
|
||||
}
|
||||
expect(first.partition).not.toContain('private.example')
|
||||
})
|
||||
|
||||
it('keeps delimiter-containing components structurally distinct', () => {
|
||||
const left = deriveBrowserRoutePartition({
|
||||
...identity,
|
||||
@@ -49,17 +35,6 @@ describe('browser route partition identity', () => {
|
||||
expect(left).not.toEqual(right)
|
||||
})
|
||||
|
||||
it('does not expose equality of individual identity components', () => {
|
||||
const baseline = deriveBrowserRoutePartition(identity).partition
|
||||
const sameProfile = deriveBrowserRoutePartition({
|
||||
...identity,
|
||||
executionHostIdentity: 'ssh/target:other.example'
|
||||
}).partition
|
||||
|
||||
expect(baseline.split('-').at(-1)).not.toBe(sameProfile.split('-').at(-1))
|
||||
expect(baseline).not.toMatch(/:[a-f0-9]{16}:/)
|
||||
})
|
||||
|
||||
it('makes every identity component load-bearing', () => {
|
||||
const derived = [
|
||||
identity,
|
||||
@@ -82,12 +57,6 @@ describe('browser route partition identity', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the partition name and the binding fingerprint in separate digest domains', () => {
|
||||
const derived = deriveBrowserRoutePartition(identity)
|
||||
|
||||
expect(derived.partition).not.toContain(derived.bindingFingerprint)
|
||||
})
|
||||
|
||||
it('scopes partition ownership to one orca profile and one environment', () => {
|
||||
const scope = deriveBrowserRoutePartitionStorageScope({
|
||||
orcaProfileId: 'orca/profile:alpha',
|
||||
|
||||
@@ -36,10 +36,6 @@ describe('registrable family across public-suffix sections', () => {
|
||||
expect(registrableFamily('[::1]')).toBe('[::1]')
|
||||
})
|
||||
|
||||
it('treats an unlisted suffix as its own boundary', () => {
|
||||
expect(registrableFamily('example.notaruleatall')).toBe('example.notaruleatall')
|
||||
})
|
||||
|
||||
it('rejects a bare suffix as an import domain but keeps real hosts', () => {
|
||||
expect(normalizeCookieImportDomain('co.uk')).toBeNull()
|
||||
expect(normalizeCookieImportDomain('api.br')).toBeNull()
|
||||
@@ -50,11 +46,6 @@ describe('registrable family across public-suffix sections', () => {
|
||||
|
||||
// Unlisted .local uses a two-label family boundary.
|
||||
describe('unlisted .local suffix', () => {
|
||||
it('stops at the two-label boundary', () => {
|
||||
expect(registrableFamily('app.orca.local')).toBe('orca.local')
|
||||
expect(registrableFamily('orca.local')).toBe('orca.local')
|
||||
})
|
||||
|
||||
it('pulls the shared parent into the removal scope', () => {
|
||||
const scope = importedDomainScope(['app.orca.local'])
|
||||
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
import { mkdtempSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({ userData: '', emit: vi.fn() }))
|
||||
|
||||
vi.mock('electron', () => ({ app: { getPath: () => mocks.userData, on: vi.fn() } }))
|
||||
vi.mock('./browser-extension-api-host', () => ({
|
||||
emitBrowserExtensionWorkerStartEvent: mocks.emit
|
||||
}))
|
||||
|
||||
mocks.userData = mkdtempSync(join(tmpdir(), 'orca-extension-lifecycle-'))
|
||||
|
||||
const { decideRuntimeLifecycleEvents, fireRuntimeLifecycleEvents } =
|
||||
await import('./browser-extension-runtime-lifecycle')
|
||||
const { getBrowserExtensionProfileStateStore } =
|
||||
await import('./browser-extension-profile-state-store')
|
||||
|
||||
const loaded = (extensionVersion: string, chromiumVersion = '140.0.0.0') => ({
|
||||
extensionVersion,
|
||||
chromiumVersion
|
||||
})
|
||||
const install = { event: 'onInstalled', args: [{ reason: 'install' }] }
|
||||
const startup = { event: 'onStartup', args: [] }
|
||||
|
||||
describe('decideRuntimeLifecycleEvents', () => {
|
||||
it('installs on the first load in a profile, with no onStartup even at launch', () => {
|
||||
expect(decideRuntimeLifecycleEvents(undefined, loaded('1.0'), 'startup')).toEqual([install])
|
||||
expect(decideRuntimeLifecycleEvents(undefined, loaded('1.0'), 'other')).toEqual([install])
|
||||
})
|
||||
|
||||
it('fires only onStartup when an installed extension loads at launch unchanged', () => {
|
||||
expect(decideRuntimeLifecycleEvents(loaded('1.0'), loaded('1.0'), 'startup')).toEqual([startup])
|
||||
expect(decideRuntimeLifecycleEvents(loaded('1.0'), loaded('1.0'), 'other')).toEqual([])
|
||||
})
|
||||
|
||||
it('reports a new version, or any reload, as an update with the previous version', () => {
|
||||
const update = { event: 'onInstalled', args: [{ reason: 'update', previousVersion: '1.0' }] }
|
||||
expect(decideRuntimeLifecycleEvents(loaded('1.0'), loaded('2.0'), 'reload')).toEqual([update])
|
||||
expect(decideRuntimeLifecycleEvents(loaded('1.0'), loaded('1.0'), 'reload')).toEqual([update])
|
||||
expect(decideRuntimeLifecycleEvents(loaded('1.0'), loaded('2.0'), 'startup')).toEqual([
|
||||
startup,
|
||||
update
|
||||
])
|
||||
})
|
||||
|
||||
it('reports a new Chromium under the same extension version as chrome_update', () => {
|
||||
expect(
|
||||
decideRuntimeLifecycleEvents(loaded('1.0', '139.0'), loaded('1.0', '140.0'), 'startup')
|
||||
).toEqual([startup, { event: 'onInstalled', args: [{ reason: 'chrome_update' }] }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('fireRuntimeLifecycleEvents', () => {
|
||||
const session: Electron.Session = Object.create(null)
|
||||
const extension = (version: string, background: unknown = { service_worker: 'w.js' }) =>
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the firing reads only id, version and manifest.background.
|
||||
({ id: 'a'.repeat(32), version, manifest: { background } }) as unknown as Electron.Extension
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.emit.mockClear()
|
||||
getBrowserExtensionProfileStateStore().forgetExtension('a'.repeat(32))
|
||||
})
|
||||
|
||||
it('records what it fired so the same launch never fires it twice', () => {
|
||||
fireRuntimeLifecycleEvents(session, 'default', extension('1.0'), 'other')
|
||||
fireRuntimeLifecycleEvents(session, 'default', extension('1.0'), 'other')
|
||||
expect(mocks.emit.mock.calls).toEqual([
|
||||
[session, 'a'.repeat(32), 'runtime', 'onInstalled', [{ reason: 'install' }]]
|
||||
])
|
||||
expect(
|
||||
getBrowserExtensionProfileStateStore().read('default', 'a'.repeat(32)).lastLoaded
|
||||
).toEqual({ extensionVersion: '1.0', chromiumVersion: process.versions.chrome })
|
||||
})
|
||||
|
||||
it('keeps each profile apart and is cleared with the extension', () => {
|
||||
fireRuntimeLifecycleEvents(session, 'default', extension('1.0'), 'other')
|
||||
fireRuntimeLifecycleEvents(session, 'work', extension('1.0'), 'startup')
|
||||
getBrowserExtensionProfileStateStore().forgetExtension('a'.repeat(32))
|
||||
fireRuntimeLifecycleEvents(session, 'default', extension('1.0'), 'startup')
|
||||
expect(mocks.emit.mock.calls.map((call) => [call[3], call[4]])).toEqual([
|
||||
['onInstalled', [{ reason: 'install' }]],
|
||||
['onInstalled', [{ reason: 'install' }]],
|
||||
['onInstalled', [{ reason: 'install' }]]
|
||||
])
|
||||
})
|
||||
|
||||
it('records but raises nothing for an extension without a service worker', () => {
|
||||
fireRuntimeLifecycleEvents(session, 'default', extension('1.0', null), 'other')
|
||||
expect(mocks.emit).not.toHaveBeenCalled()
|
||||
expect(
|
||||
getBrowserExtensionProfileStateStore().read('default', 'a'.repeat(32)).lastLoaded
|
||||
).toBeDefined()
|
||||
})
|
||||
})
|
||||
@@ -27,7 +27,7 @@ vi.mock('./browser-extension-webstore-install', () => ({
|
||||
isBrowserExtensionBusy: () => false
|
||||
}))
|
||||
|
||||
const { checkForBrowserExtensionUpdates, compareExtensionVersions, parseOmahaUpdateResponse } =
|
||||
const { checkForBrowserExtensionUpdates, parseOmahaUpdateResponse } =
|
||||
await import('./browser-extension-webstore-updater')
|
||||
|
||||
const UBOL = 'ddkjiahejlhfcafbddmgiahcphecmpfh'
|
||||
@@ -64,38 +64,7 @@ ${JSON.stringify({
|
||||
}
|
||||
})}`
|
||||
|
||||
describe('compareExtensionVersions', () => {
|
||||
it('compares dotted integers numerically', () => {
|
||||
expect(compareExtensionVersions('2026.1018.2229', '2026.1018.2228')).toBe(1)
|
||||
expect(compareExtensionVersions('1.10', '1.9')).toBe(1)
|
||||
expect(compareExtensionVersions('1.0', '1')).toBe(0)
|
||||
expect(compareExtensionVersions('1.0.0.1', '1.0.1')).toBe(-1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseOmahaUpdateResponse', () => {
|
||||
it('offers newer versions with the package URL, size and checksum', () => {
|
||||
const installed = new Map([
|
||||
[UBOL, '2026.1001.1'],
|
||||
[BITWARDEN, '2026.1.0']
|
||||
])
|
||||
expect(parseOmahaUpdateResponse(RESPONSE, installed)).toEqual([
|
||||
{
|
||||
extensionId: UBOL,
|
||||
version: '2026.1018.2229',
|
||||
url: 'https://clients2.googleusercontent.com/crx/blobs/AZPV/DDKJIAHEJLHFCAFBDDMGIAHCPHECMPFH_2026_1018_2229_0.crx',
|
||||
sha256: '559d10ef7dcb96bc4e812de6b3ff0c2e6c7abca578324d8d7afd7d8cf78a6dd7',
|
||||
size: 9145194
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('skips versions that are not newer, unknown apps and malformed replies', () => {
|
||||
expect(parseOmahaUpdateResponse(RESPONSE, new Map([[UBOL, '2026.1018.2229']]))).toEqual([])
|
||||
expect(parseOmahaUpdateResponse(RESPONSE, new Map())).toEqual([])
|
||||
expect(parseOmahaUpdateResponse('not json', new Map([[UBOL, '1']]))).toEqual([])
|
||||
})
|
||||
|
||||
it('drops download URLs outside Google hosts', () => {
|
||||
const hostile = RESPONSE.replace(
|
||||
'https://clients2.googleusercontent.com/crx/blobs/AZPV/',
|
||||
|
||||
@@ -197,31 +197,6 @@ describe('context usage across a restart', () => {
|
||||
after.release()
|
||||
})
|
||||
|
||||
it('keeps the last known size of a turn the child crashed in', async () => {
|
||||
const journal = await openJournal()
|
||||
const crashed = acquire(journal)
|
||||
crashed.translator.handle(initFrame(900))
|
||||
crashed.translator.handle(userFrame('turn-a', 1_000))
|
||||
crashed.translator.handle(assistantFrame('reply-a', 2_000, 20_000))
|
||||
crashed.translator.handle(resultFrame(3_000))
|
||||
crashed.translator.handle(initFrame(3900))
|
||||
crashed.translator.handle(userFrame('turn-b', 4_000))
|
||||
crashed.translator.handle(assistantFrame('reply-b', 5_000, 120_000))
|
||||
await crashed.settle()
|
||||
crashed.release()
|
||||
|
||||
await settleStaleStructuredAgentSessionState({
|
||||
journal,
|
||||
sessionId: 'orca-session',
|
||||
fence: 2,
|
||||
acquisitionGeneration: 'next',
|
||||
deathEvidence: null
|
||||
})
|
||||
const turns = journal.snapshot().items.map((item) => readAgentJournalTurn(item.body)?.state)
|
||||
expect(turns).toContain('unverifiable')
|
||||
expect(ring(journal)).toMatchObject({ usedTokens: 120_000, windowTokens: 1_000_000 })
|
||||
})
|
||||
|
||||
it('never brings a settled turn back to running with a context write that ran late', async () => {
|
||||
const journal = await openJournal()
|
||||
const live = acquire(journal)
|
||||
@@ -251,21 +226,6 @@ describe('context usage across a restart', () => {
|
||||
live.release()
|
||||
})
|
||||
|
||||
it("reads a new session's implied window the same from its loaded rows and from the host", async () => {
|
||||
const journal = await openJournal()
|
||||
const live = acquire(journal)
|
||||
live.translator.modelWritten('opus[1m]')
|
||||
live.translator.handle(initFrame(900))
|
||||
live.translator.handle(userFrame('turn-a', 1_000))
|
||||
live.translator.handle(assistantFrame('reply-a', 2_000, 150_000))
|
||||
await live.settle()
|
||||
const expected = { usedTokens: 150_000, windowTokens: 1_000_000, percentage: 15 }
|
||||
expect(ring(journal)).toMatchObject(expected)
|
||||
expect(journal.contextUsage()).toMatchObject({ window: { tokens: 1_000_000 } })
|
||||
expect(selectStructuredAgentContextUsage([], journal.contextUsage())).toMatchObject(expected)
|
||||
live.release()
|
||||
})
|
||||
|
||||
it('keeps the window a restarted journal holds over the one the model name implies', async () => {
|
||||
const journal = await openJournal()
|
||||
const before = acquire(journal)
|
||||
|
||||
@@ -53,19 +53,6 @@ function modelValue(result: AgentSessionOptionsResult): string | undefined {
|
||||
}
|
||||
|
||||
describe('structured option confirmation reaches the pill', () => {
|
||||
it('shows a just-set model before any turn reports it', async () => {
|
||||
const claude = fakeClaude({
|
||||
initModel: 'claude-sonnet-5',
|
||||
routes: { list_models: () => CATALOG }
|
||||
})
|
||||
const adapter = await acquired(claude)
|
||||
await adapter.setOption({ sessionId: 'session-1', key: 'model', value: 'haiku', fence: 7 })
|
||||
|
||||
const result = await adapter.readOptions({ sessionId: 'session-1', fence: 7 })
|
||||
expect(result.current.confirmed ?? []).not.toContain('model')
|
||||
expect(modelSource(result)).toBe('dispatched')
|
||||
})
|
||||
|
||||
it('marks the model reported once the provider names it back', async () => {
|
||||
const claude = fakeClaude({
|
||||
initModel: 'claude-sonnet-5',
|
||||
@@ -79,46 +66,6 @@ describe('structured option confirmation reaches the pill', () => {
|
||||
expect(result.current.confirmed).toContain('model')
|
||||
expect(modelSource(result)).toBe('reported')
|
||||
})
|
||||
|
||||
it('records an effort the readback could not take without confirming it', async () => {
|
||||
const claude = fakeClaude({
|
||||
initModel: 'claude-sonnet-5',
|
||||
settings: { applied: {}, effective: {}, sources: {} },
|
||||
routes: { list_models: () => CATALOG }
|
||||
})
|
||||
const adapter = await acquired(claude)
|
||||
// Max is session-only and cannot be confirmed through persisted settings.
|
||||
await adapter.setOption({ sessionId: 'session-1', key: 'effort', value: 'max', fence: 7 })
|
||||
|
||||
const result = await adapter.readOptions({ sessionId: 'session-1', fence: 7 })
|
||||
expect(result.current.effort).toBe('max')
|
||||
expect(result.current.confirmed ?? []).not.toContain('effort')
|
||||
})
|
||||
|
||||
it('confirms an effort the readback agreed with', async () => {
|
||||
const claude = fakeClaude({
|
||||
initModel: 'claude-sonnet-5',
|
||||
settings: { applied: { effort: 'low' }, effective: { effortLevel: 'low' }, sources: {} },
|
||||
routes: { list_models: () => CATALOG }
|
||||
})
|
||||
const adapter = await acquired(claude)
|
||||
await adapter.setOption({ sessionId: 'session-1', key: 'effort', value: 'low', fence: 7 })
|
||||
|
||||
await vi.waitFor(async () => {
|
||||
const result = await adapter.readOptions({ sessionId: 'session-1', fence: 7 })
|
||||
expect(result.current.confirmed).toContain('effort')
|
||||
})
|
||||
})
|
||||
|
||||
it('treats a host that reports no confirmation as unconfirmed', () => {
|
||||
// Older hosts omit confirmed; preserve their value with unconfirmed provenance.
|
||||
const result = {
|
||||
models: [{ id: 'haiku', label: 'Haiku', isDefault: false, efforts: [] }],
|
||||
current: { model: 'haiku' }
|
||||
}
|
||||
expect(modelSource(result)).toBe('dispatched')
|
||||
expect(modelValue(result)).toBe('haiku')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the provider report corrects the pill', () => {
|
||||
|
||||
@@ -2,21 +2,6 @@ import { describe, expect, it } from 'vitest'
|
||||
import { ClaudeSubagentIds } from './claude-subagent-id-aliases'
|
||||
|
||||
describe('ClaudeSubagentIds', () => {
|
||||
it('resolves an aliased tool id to its task, and an unaliased id to itself', () => {
|
||||
const ids = new ClaudeSubagentIds()
|
||||
ids.alias('toolu_1', 'task-1')
|
||||
expect(ids.canonical('toolu_1')).toBe('task-1')
|
||||
expect(ids.canonical('toolu_unknown')).toBe('toolu_unknown')
|
||||
})
|
||||
|
||||
it('remembers an exclusion under either of the ids that named it', () => {
|
||||
const ids = new ClaudeSubagentIds()
|
||||
ids.exclude('task-bash')
|
||||
expect(ids.isExcluded('toolu_bash', 'task-bash')).toBe(true)
|
||||
expect(ids.isExcluded(null, null)).toBe(false)
|
||||
expect(ids.isExcluded('task-agent')).toBe(false)
|
||||
})
|
||||
|
||||
it('drops the oldest alias past the bound and keeps the newest', () => {
|
||||
const ids = new ClaudeSubagentIds()
|
||||
for (let index = 0; index <= 512; index += 1) {
|
||||
@@ -47,15 +32,6 @@ describe('ClaudeSubagentIds', () => {
|
||||
expect(ids.canonical('tool-1')).toBe('tool-1')
|
||||
expect(ids.isExcluded(oversized)).toBe(false)
|
||||
})
|
||||
|
||||
it('forgets everything on clear', () => {
|
||||
const ids = new ClaudeSubagentIds()
|
||||
ids.alias('toolu_1', 'task-1')
|
||||
ids.exclude('task-1')
|
||||
ids.clear()
|
||||
expect(ids.canonical('toolu_1')).toBe('toolu_1')
|
||||
expect(ids.isExcluded('task-1')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ClaudeSubagentIds with an earlier run journaled', () => {
|
||||
|
||||
@@ -24,6 +24,7 @@ describe('reconcileManagedWslCliRegistrations', () => {
|
||||
isPackaged: true,
|
||||
userDataPath: '/user-data',
|
||||
listDistros: async () => ['Ubuntu', 'Debian', 'Fedora'],
|
||||
listOrcaHostDistros: () => ['Debian'],
|
||||
listRunningDistros: async () => ['Ubuntu', 'Debian', 'Fedora'],
|
||||
isDistroRunning: async (distro: string) => ['Ubuntu', 'Debian', 'Fedora'].includes(distro),
|
||||
registry,
|
||||
@@ -37,7 +38,8 @@ describe('reconcileManagedWslCliRegistrations', () => {
|
||||
|
||||
expect(registry.getCandidates).toHaveBeenCalledWith(['Ubuntu', 'Debian', 'Fedora'], {
|
||||
currentTarget: null,
|
||||
appVersion: ''
|
||||
appVersion: '',
|
||||
inspectableDistros: ['Debian']
|
||||
})
|
||||
expect(registry.recordObservations).toHaveBeenCalledTimes(2)
|
||||
expect(registry.recordObservations).toHaveBeenCalledWith([
|
||||
@@ -195,6 +197,7 @@ describe('reconcileManagedWslCliRegistrations', () => {
|
||||
isPackaged: true,
|
||||
userDataPath: '/user-data',
|
||||
listDistros: async () => ['Ubuntu', 'Debian'],
|
||||
listOrcaHostDistros: () => [],
|
||||
listRunningDistros: async () => running,
|
||||
isDistroRunning: async (distro: string) => running.includes(distro),
|
||||
deferUntilRunning: (distro: string, _key: string, task: () => unknown) => {
|
||||
@@ -221,7 +224,8 @@ describe('reconcileManagedWslCliRegistrations', () => {
|
||||
expect(repaired).toEqual(['Ubuntu', 'Debian'])
|
||||
expect(registry.getCandidates).toHaveBeenLastCalledWith(['Debian'], {
|
||||
currentTarget: null,
|
||||
appVersion: ''
|
||||
appVersion: '',
|
||||
inspectableDistros: []
|
||||
})
|
||||
})
|
||||
|
||||
@@ -255,4 +259,30 @@ describe('reconcileManagedWslCliRegistrations', () => {
|
||||
expect(deferred).toEqual(['Debian'])
|
||||
expect(results).toContainEqual({ distro: 'Debian', outcome: 'deferred' })
|
||||
})
|
||||
|
||||
it("asks the registry to inspect only distros Orca deployed a host into, read from the user's store", async () => {
|
||||
const registry = {
|
||||
getCandidates: vi.fn(async () => []),
|
||||
recordObservations: vi.fn(async () => undefined)
|
||||
}
|
||||
const createInstaller = vi.fn()
|
||||
|
||||
await reconcileManagedWslCliRegistrations({
|
||||
platform: 'win32',
|
||||
isPackaged: true,
|
||||
userDataPath: '/user-data-without-hosts',
|
||||
listDistros: async () => ['Ubuntu', 'MyDevBox'],
|
||||
getHostLauncherTarget: async () => null,
|
||||
registry,
|
||||
createInstaller
|
||||
})
|
||||
|
||||
// No deployment store exists for this profile: no host, so no distro is inspectable.
|
||||
expect(registry.getCandidates).toHaveBeenCalledWith(['Ubuntu', 'MyDevBox'], {
|
||||
currentTarget: null,
|
||||
appVersion: '',
|
||||
inspectableDistros: []
|
||||
})
|
||||
expect(createInstaller).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} from './wsl-cli-registration-registry'
|
||||
import { WslCliInstaller } from './wsl-cli-installer'
|
||||
import { runSerializedWslCliRegistrationOperation } from './wsl-cli-registration-operation'
|
||||
import { readWslHostDeployments } from '../../shared/wsl-host-deployment-store'
|
||||
|
||||
// Why: each repair spawns a guest shell; a small cap bounds the startup fan-out.
|
||||
const MAX_CONCURRENT_DISTRO_REPAIRS = 2
|
||||
@@ -29,6 +30,7 @@ type ManagedWslCliInstaller = {
|
||||
type WslCliRegistrationCandidateContext = {
|
||||
currentTarget?: string | null
|
||||
appVersion?: string | null
|
||||
inspectableDistros?: readonly string[]
|
||||
}
|
||||
|
||||
type WslCliRegistrationRegistry = {
|
||||
@@ -48,6 +50,8 @@ type WslCliRegistrationReconciliationOptions = {
|
||||
createInstaller?: (distro: string) => ManagedWslCliInstaller
|
||||
getHostLauncherTarget?: () => Promise<string | null>
|
||||
registry?: WslCliRegistrationRegistry
|
||||
/** Distros Orca deployed a WSL host into; only those may be inspected for an unrecorded registration. */
|
||||
listOrcaHostDistros?: () => string[]
|
||||
listRunningDistros?: () => Promise<string[]>
|
||||
/** Settled read taken right before each repair spawns. */
|
||||
isDistroRunning?: (distro: string) => Promise<boolean>
|
||||
@@ -112,7 +116,14 @@ export async function reconcileManagedWslCliRegistrations(
|
||||
? await getHostLauncherTarget().catch(() => null)
|
||||
: null
|
||||
const appVersion = options.appVersion ?? ''
|
||||
const candidates = await registry.getCandidates(availableDistros, { currentTarget, appVersion })
|
||||
const inspectableDistros = (
|
||||
options.listOrcaHostDistros ?? (() => orcaHostDistros(options.userDataPath))
|
||||
)()
|
||||
const candidates = await registry.getCandidates(availableDistros, {
|
||||
currentTarget,
|
||||
appVersion,
|
||||
inspectableDistros
|
||||
})
|
||||
if (candidates.length === 0) {
|
||||
return []
|
||||
}
|
||||
@@ -206,6 +217,15 @@ export async function reconcileManagedWslCliRegistrations(
|
||||
return [...results, ...deferred]
|
||||
}
|
||||
|
||||
function orcaHostDistros(userDataPath: string): string[] {
|
||||
try {
|
||||
return readWslHostDeployments(userDataPath).deployments.map((record) => record.distro)
|
||||
} catch {
|
||||
// An unreadable store names no host; registered distros are still reconciled.
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export function logWslCliReconciliationResults(
|
||||
results: readonly WslCliRegistrationReconciliationResult[]
|
||||
): void {
|
||||
|
||||
@@ -76,13 +76,15 @@ describe('WSL CLI registration registry', () => {
|
||||
await expect(
|
||||
getWslCliRegistrationCandidates(userDataPath, ['Fedora'], {
|
||||
now: 2_000,
|
||||
negativeInspectionTtlMs: 10_000
|
||||
negativeInspectionTtlMs: 10_000,
|
||||
inspectableDistros: ['Fedora']
|
||||
})
|
||||
).resolves.toEqual([])
|
||||
await expect(
|
||||
getWslCliRegistrationCandidates(userDataPath, ['Fedora'], {
|
||||
now: 12_000,
|
||||
negativeInspectionTtlMs: 10_000
|
||||
negativeInspectionTtlMs: 10_000,
|
||||
inspectableDistros: ['Fedora']
|
||||
})
|
||||
).resolves.toEqual(['Fedora'])
|
||||
})
|
||||
@@ -99,7 +101,9 @@ describe('WSL CLI registration registry', () => {
|
||||
|
||||
// Reads join the write queue, so startup cannot observe a half-updated registry.
|
||||
await expect(
|
||||
getWslCliRegistrationCandidates(userDataPath, ['Ubuntu', 'Debian'])
|
||||
getWslCliRegistrationCandidates(userDataPath, ['Ubuntu', 'Debian'], {
|
||||
inspectableDistros: ['Ubuntu', 'Debian']
|
||||
})
|
||||
).resolves.toEqual(['Ubuntu', 'Debian'])
|
||||
await updates
|
||||
const state = JSON.parse(
|
||||
@@ -113,7 +117,9 @@ describe('WSL CLI registration registry', () => {
|
||||
await writeFile(join(userDataPath, 'wsl-cli-registrations.json'), '{broken', 'utf8')
|
||||
|
||||
await expect(
|
||||
getWslCliRegistrationCandidates(userDataPath, ['Ubuntu', 'Debian'])
|
||||
getWslCliRegistrationCandidates(userDataPath, ['Ubuntu', 'Debian'], {
|
||||
inspectableDistros: ['Ubuntu', 'Debian']
|
||||
})
|
||||
).resolves.toEqual(['Ubuntu', 'Debian'])
|
||||
})
|
||||
|
||||
@@ -159,13 +165,15 @@ describe('WSL CLI registration registry', () => {
|
||||
await expect(
|
||||
getWslCliRegistrationCandidates(userDataPath, ['Ubuntu'], {
|
||||
now: 1_001,
|
||||
negativeInspectionTtlMs: 10_000
|
||||
negativeInspectionTtlMs: 10_000,
|
||||
inspectableDistros: ['Ubuntu']
|
||||
})
|
||||
).resolves.toEqual([])
|
||||
await expect(
|
||||
getWslCliRegistrationCandidates(userDataPath, ['Ubuntu'], {
|
||||
now: 11_001,
|
||||
negativeInspectionTtlMs: 10_000
|
||||
negativeInspectionTtlMs: 10_000,
|
||||
inspectableDistros: ['Ubuntu']
|
||||
})
|
||||
).resolves.toEqual(['Ubuntu'])
|
||||
})
|
||||
@@ -184,7 +192,8 @@ describe('WSL CLI registration registry', () => {
|
||||
await expect(
|
||||
getWslCliRegistrationCandidates(userDataPath, ['Ubuntu', 'Debian'], {
|
||||
now: 1,
|
||||
negativeInspectionTtlMs: 1_000_000
|
||||
negativeInspectionTtlMs: 1_000_000,
|
||||
inspectableDistros: ['Ubuntu', 'Debian']
|
||||
})
|
||||
).resolves.toEqual(['Ubuntu', 'Debian'])
|
||||
})
|
||||
@@ -211,4 +220,23 @@ describe('WSL CLI registration registry', () => {
|
||||
expect(Object.keys(state.inspectionTimes).length).toBeLessThanOrEqual(65)
|
||||
expect(state.inspectionTimes['managed oldest']).toBe(0)
|
||||
})
|
||||
|
||||
it("never inspects a distro Orca has no record of: the user's own distros get no guest command", async () => {
|
||||
await expect(
|
||||
getWslCliRegistrationCandidates(userDataPath, ['Ubuntu', 'MyDevBox'], {
|
||||
inspectableDistros: ['Ubuntu']
|
||||
})
|
||||
).resolves.toEqual(['Ubuntu'])
|
||||
await expect(getWslCliRegistrationCandidates(userDataPath, ['MyDevBox'])).resolves.toEqual([])
|
||||
})
|
||||
|
||||
it("still reconciles a distro carrying Orca's own registration record", async () => {
|
||||
await recordWslCliRegistrationObservations(userDataPath, [
|
||||
{ distro: 'Ubuntu', inspected: true, managed: true, reconciled: null }
|
||||
])
|
||||
|
||||
await expect(getWslCliRegistrationCandidates(userDataPath, ['Ubuntu'])).resolves.toEqual([
|
||||
'Ubuntu'
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -28,6 +28,11 @@ type WslCliRegistrationRegistryTiming = {
|
||||
// Unchanged launcher/build pairs need no repair; app updates must trigger a new probe.
|
||||
currentTarget?: string | null
|
||||
appVersion?: string | null
|
||||
/**
|
||||
* Unregistered distros that may still be inspected: ones Orca deployed a host into. Any other
|
||||
* distro is the user's own and never gets a guest command (EDR noise, untouched environments).
|
||||
*/
|
||||
inspectableDistros?: readonly string[]
|
||||
}
|
||||
|
||||
export type WslCliRegistrationObservation = {
|
||||
@@ -193,6 +198,7 @@ export async function getWslCliRegistrationCandidates(
|
||||
const now = timing.now ?? Date.now()
|
||||
const negativeInspectionTtlMs =
|
||||
timing.negativeInspectionTtlMs ?? DEFAULT_NEGATIVE_INSPECTION_TTL_MS
|
||||
const inspectable = new Set((timing.inspectableDistros ?? []).map(normalizeWslDistroKey))
|
||||
return uniqueDistros(availableDistros).filter((distro) => {
|
||||
const key = normalizeWslDistroKey(distro)
|
||||
if (registered.has(key)) {
|
||||
@@ -204,6 +210,9 @@ export async function getWslCliRegistrationCandidates(
|
||||
reconciliation.appVersion === (timing.appVersion ?? '')
|
||||
)
|
||||
}
|
||||
if (!inspectable.has(key)) {
|
||||
return false
|
||||
}
|
||||
const inspectedAt = state.inspectionTimes[key]
|
||||
return (
|
||||
inspectedAt === undefined || inspectedAt > now || now - inspectedAt >= negativeInspectionTtlMs
|
||||
|
||||
@@ -4,9 +4,9 @@ import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import {
|
||||
buildCodexRolloutResumeState,
|
||||
MIN_RESUMABLE_PREFIX_BYTES,
|
||||
resolveCodexRolloutResume
|
||||
} from './codex-rollout-resume-state'
|
||||
|
||||
import type { CodexUsageParseContext } from './codex-usage-record-parser'
|
||||
import type { CodexUsagePersistedFile } from './types'
|
||||
|
||||
@@ -71,28 +71,6 @@ describe('buildCodexRolloutResumeState', () => {
|
||||
buildCodexRolloutResumeState(filePath, 5 * WINDOW_BYTES, context)
|
||||
).resolves.toBeNull()
|
||||
})
|
||||
|
||||
// Digest verification costs more than rereading a short prefix.
|
||||
it('refuses a prefix at or under the resumable floor', async () => {
|
||||
const filePath = writeRollout('at-floor.jsonl', 4 * WINDOW_BYTES)
|
||||
|
||||
expect(MIN_RESUMABLE_PREFIX_BYTES).toBe(3 * WINDOW_BYTES)
|
||||
await expect(
|
||||
buildCodexRolloutResumeState(filePath, MIN_RESUMABLE_PREFIX_BYTES, context)
|
||||
).resolves.toBeNull()
|
||||
await expect(
|
||||
buildCodexRolloutResumeState(filePath, MIN_RESUMABLE_PREFIX_BYTES + 1, context)
|
||||
).resolves.not.toBeNull()
|
||||
})
|
||||
|
||||
it('records an offset the file still reaches', async () => {
|
||||
const filePath = writeRollout('full-prefix.jsonl', 4 * WINDOW_BYTES)
|
||||
|
||||
const state = await buildCodexRolloutResumeState(filePath, 4 * WINDOW_BYTES, context)
|
||||
|
||||
expect(state?.parsedBytes).toBe(4 * WINDOW_BYTES)
|
||||
expect(state?.headDigest).toMatch(new RegExp(`^${WINDOW_BYTES}:`))
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveCodexRolloutResume', () => {
|
||||
@@ -107,24 +85,6 @@ describe('resolveCodexRolloutResume', () => {
|
||||
await expect(resolveCodexRolloutResume(filePath, previous)).resolves.toBeNull()
|
||||
})
|
||||
|
||||
// Validate untrusted cache offsets before calculating the boundary window.
|
||||
it('rejects a persisted offset under the floor', async () => {
|
||||
const filePath = writeRollout('under-floor.jsonl', 4 * WINDOW_BYTES)
|
||||
const previous = persistedFile(filePath, {
|
||||
parsedBytes: 100,
|
||||
boundaryDigest: `${WINDOW_BYTES}:unused`,
|
||||
headDigest: `${WINDOW_BYTES}:unused`,
|
||||
physicalFileId: null,
|
||||
sessionId: 'session-under-floor',
|
||||
sessionCwd: null,
|
||||
currentCwd: null,
|
||||
currentModel: null,
|
||||
previousTotals: null
|
||||
})
|
||||
|
||||
await expect(resolveCodexRolloutResume(filePath, previous)).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('accepts a recorded offset when the file only grew', async () => {
|
||||
const filePath = writeRollout('grown.jsonl', 4 * WINDOW_BYTES)
|
||||
const state = await buildCodexRolloutResumeState(filePath, 4 * WINDOW_BYTES, context)
|
||||
|
||||
@@ -32,37 +32,6 @@ describe('renderer crash breadcrumb attribution', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('does not merge identical coalesced storms from sibling renderers', () => {
|
||||
recordCoalescedCrashBreadcrumb({
|
||||
name: 'renderer_error',
|
||||
data: { message: 'boom' },
|
||||
coalesceKey: 'renderer:11\u0000renderer_error:boom',
|
||||
minIntervalMs: 30_000,
|
||||
origin: 'renderer:11'
|
||||
})
|
||||
recordCoalescedCrashBreadcrumb({
|
||||
name: 'renderer_error',
|
||||
data: { message: 'boom' },
|
||||
coalesceKey: 'renderer:22\u0000renderer_error:boom',
|
||||
minIntervalMs: 30_000,
|
||||
origin: 'renderer:22'
|
||||
})
|
||||
|
||||
expect(getCrashBreadcrumbSnapshot('renderer:11')).toHaveLength(1)
|
||||
expect(getCrashBreadcrumbSnapshot('renderer:22')).toHaveLength(1)
|
||||
expect(getCrashBreadcrumbSnapshot('renderer:11')[0]?.origin).toBe('renderer:11')
|
||||
expect(getCrashBreadcrumbSnapshot('renderer:22')[0]?.origin).toBe('renderer:22')
|
||||
})
|
||||
|
||||
it('retains identical high-water profiles independently per renderer', () => {
|
||||
const profile = { rendererSurface: 'main', thresholdPct: 80, usedHeapMB: 512 }
|
||||
recordCrashBreadcrumb('renderer_memory_highwater', profile, 'renderer:11')
|
||||
recordCrashBreadcrumb('renderer_memory_highwater', profile, 'renderer:22')
|
||||
|
||||
expect(getCrashBreadcrumbSnapshot('renderer:11')[0]?.origin).toBe('renderer:11')
|
||||
expect(getCrashBreadcrumbSnapshot('renderer:22')[0]?.origin).toBe('renderer:22')
|
||||
})
|
||||
|
||||
it('preserves the reporter trail when sibling renderer traffic fills the ring', () => {
|
||||
for (let index = 0; index < 4; index += 1) {
|
||||
recordCrashBreadcrumb('renderer_memory_highwater', {
|
||||
|
||||
@@ -3,10 +3,7 @@ import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { resolveAppImageExtractedRoot } from '../cli/appimage-extracted-root'
|
||||
import {
|
||||
buildAppImageGenerationDaemonCommand,
|
||||
resolveAppImageGenerationDaemonLaunch
|
||||
} from './daemon-appimage-generation-launch'
|
||||
import { resolveAppImageGenerationDaemonLaunch } from './daemon-appimage-generation-launch'
|
||||
|
||||
const { resolveIdentity } = vi.hoisted(() => ({ resolveIdentity: vi.fn() }))
|
||||
vi.mock('../appimage-runtime-identity', () => ({ resolveAppImageRuntimeIdentity: resolveIdentity }))
|
||||
@@ -61,32 +58,6 @@ function extractGeneration(options: { node?: boolean; version?: string } = {}):
|
||||
}
|
||||
|
||||
describe('resolveAppImageGenerationDaemonLaunch', () => {
|
||||
it('runs the daemon on the bundled Node of the extracted copy of this AppImage', () => {
|
||||
const generation = extractGeneration()
|
||||
expect(resolveAppImageGenerationDaemonLaunch(input())).toEqual({
|
||||
launch: {
|
||||
generationRoot: generation,
|
||||
nodePath: join(generation, 'resources', 'node-runtime', 'bin', 'node'),
|
||||
entryPath: join(generation, ENTRY_IN_APPDIR),
|
||||
// Match own-mount identity so either host can be adopted.
|
||||
identityPath: join(appImagePath, ENTRY_IN_APPDIR)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('says nothing off a validated AppImage', () => {
|
||||
extractGeneration()
|
||||
resolveIdentity.mockReturnValue(null)
|
||||
expect(resolveAppImageGenerationDaemonLaunch(input())).toBeNull()
|
||||
expect(resolveAppImageGenerationDaemonLaunch(input({ environment: {} }))).toBeNull()
|
||||
})
|
||||
|
||||
it('falls back when the AppImage was never extracted', () => {
|
||||
expect(resolveAppImageGenerationDaemonLaunch(input())).toEqual({
|
||||
fallback: 'no-extracted-copy'
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back when the extracted copy predates the bundled Node', () => {
|
||||
extractGeneration({ node: false })
|
||||
expect(resolveAppImageGenerationDaemonLaunch(input())).toEqual({
|
||||
@@ -101,29 +72,3 @@ describe('resolveAppImageGenerationDaemonLaunch', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildAppImageGenerationDaemonCommand', () => {
|
||||
it.runIf(process.platform === 'linux')(
|
||||
'runs plain Node, with no Electron or AppImage runtime variables',
|
||||
() => {
|
||||
const launch = {
|
||||
generationRoot: '/cache/ns/gen',
|
||||
nodePath: '/cache/ns/gen/resources/node-runtime/bin/node',
|
||||
entryPath: `/cache/ns/gen/${ENTRY_IN_APPDIR}`,
|
||||
identityPath: `/apps/Orca.AppImage/${ENTRY_IN_APPDIR}`
|
||||
}
|
||||
const command = buildAppImageGenerationDaemonCommand(launch, ['--socket', '/s'], {
|
||||
APPDIR,
|
||||
APPIMAGE: '/apps/Orca.AppImage',
|
||||
ELECTRON_RUN_AS_NODE: '1',
|
||||
PATH: `${APPDIR}/usr/bin:/usr/bin`,
|
||||
HOME: '/home/me'
|
||||
})
|
||||
expect(command).toEqual({
|
||||
command: launch.nodePath,
|
||||
args: [launch.entryPath, '--socket', '/s'],
|
||||
env: { PATH: '/usr/bin', HOME: '/home/me' }
|
||||
})
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
@@ -3,10 +3,8 @@ import {
|
||||
DaemonProtocolError,
|
||||
decodeDaemonResponseError,
|
||||
isDaemonEndpointGoneError,
|
||||
SessionNotFoundError,
|
||||
TerminalHostGoneError
|
||||
SessionNotFoundError
|
||||
} from './daemon-errors'
|
||||
import { mapRuntimeError } from '../runtime/rpc/errors'
|
||||
|
||||
function socketError(code: string, syscall: string): Error & { code: string; syscall: string } {
|
||||
return Object.assign(new Error(`${syscall} ${code}`), { code, syscall })
|
||||
@@ -48,21 +46,4 @@ describe('isDaemonEndpointGoneError', () => {
|
||||
expect(isDaemonEndpointGoneError(socketError(code, 'connect'))).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('ignores non-socket errors and non-objects', () => {
|
||||
expect(isDaemonEndpointGoneError(new Error('Connection lost'))).toBe(false)
|
||||
expect(isDaemonEndpointGoneError('connect ENOENT')).toBe(false)
|
||||
expect(isDaemonEndpointGoneError(null)).toBe(false)
|
||||
expect(isDaemonEndpointGoneError(undefined)).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps the host-gone marker across runtime RPC error mapping', () => {
|
||||
const response = mapRuntimeError(
|
||||
'req-1',
|
||||
{ runtimeId: 'runtime-1' },
|
||||
new TerminalHostGoneError()
|
||||
)
|
||||
|
||||
expect(response.error).toEqual({ code: 'runtime_error', message: 'terminal_host_gone' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -21,15 +21,6 @@ function setup(opts: { holding: boolean; restorable?: string[]; currentSessions?
|
||||
const SPAWN = { cols: 80, rows: 24 }
|
||||
|
||||
describe('DaemonPtyRouter newer-daemon hold', () => {
|
||||
it('refuses a cold restore no adopted daemon owns while a newer daemon is held', async () => {
|
||||
const { current, router } = setup({ holding: true, restorable: ['newer-session'] })
|
||||
await router.discoverLegacySessions()
|
||||
await expect(router.spawn({ ...SPAWN, sessionId: 'newer-session' })).rejects.toThrow(
|
||||
NEWER_DAEMON_HOLD_ERROR
|
||||
)
|
||||
expect(current.spawn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
// Mobile and runtime restore can re-materialize an existing ID with its agent command.
|
||||
it('refuses an agent-launching re-materialize of that id the same way', async () => {
|
||||
const { current, router } = setup({ holding: true, restorable: ['newer-session'] })
|
||||
@@ -56,13 +47,6 @@ describe('DaemonPtyRouter newer-daemon hold', () => {
|
||||
expect(current.spawn).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('spawns fresh terminals and ids with no saved history', async () => {
|
||||
const { current, router } = setup({ holding: true })
|
||||
await router.spawn(SPAWN)
|
||||
await router.spawn({ ...SPAWN, sessionId: 'pre-allocated-new-id' })
|
||||
expect(current.spawn).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('holds when the adopted inventory cannot answer', async () => {
|
||||
const { legacy, router } = setup({ holding: true, restorable: ['newer-session'] })
|
||||
vi.mocked(legacy.listProcesses).mockRejectedValue(new Error('timeout'))
|
||||
@@ -80,11 +64,4 @@ describe('DaemonPtyRouter newer-daemon hold', () => {
|
||||
})
|
||||
expect(current.spawn).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('changes nothing for older-daemon routing when no newer daemon is held', async () => {
|
||||
const { current, router } = setup({ holding: false, restorable: ['lost-session'] })
|
||||
await router.spawn({ ...SPAWN, sessionId: 'lost-session' })
|
||||
expect(current.spawn).toHaveBeenCalledOnce()
|
||||
expect(current.hasRestorableHistory).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
import './mock-descendant-sweep'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { DaemonServer } from './daemon-server'
|
||||
import { SessionNotFoundError, type DaemonRequest } from './types'
|
||||
|
||||
type DaemonServerPrivate = {
|
||||
host: { kill: (sessionId: string, opts?: { immediate?: boolean }) => void | Promise<void> }
|
||||
preparations: {
|
||||
pending: Map<string, Set<{ canceled: boolean; clientId: string }>>
|
||||
}
|
||||
requestRouter: {
|
||||
route(clientId: string, request: DaemonRequest): Promise<unknown>
|
||||
}
|
||||
}
|
||||
|
||||
describe('daemon kill attribution', () => {
|
||||
let server: DaemonServer
|
||||
let dir: string
|
||||
|
||||
afterEach(async () => {
|
||||
await server?.shutdown()
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('records the requesting control client in the session-killed log', async () => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'daemon-kill-attribution-'))
|
||||
const killLog = { log: vi.fn(), close: vi.fn() }
|
||||
server = new DaemonServer({
|
||||
socketPath: join(dir, 'daemon.sock'),
|
||||
tokenPath: join(dir, 'daemon.token'),
|
||||
log: killLog,
|
||||
spawnSubprocess: () => {
|
||||
throw new Error('not used')
|
||||
}
|
||||
})
|
||||
const daemon = server as unknown as DaemonServerPrivate
|
||||
let finishKill!: () => void
|
||||
const killFinished = new Promise<void>((resolve) => {
|
||||
finishKill = resolve
|
||||
})
|
||||
vi.spyOn(daemon.host, 'kill').mockReturnValue(killFinished)
|
||||
|
||||
const request = daemon.requestRouter.route('control-42', {
|
||||
id: 'kill-1',
|
||||
type: 'kill',
|
||||
payload: { sessionId: 'agent-session', immediate: true }
|
||||
})
|
||||
|
||||
await vi.waitFor(() => expect(daemon.host.kill).toHaveBeenCalledOnce())
|
||||
expect(killLog.log).not.toHaveBeenCalledWith('session-killed', expect.anything())
|
||||
finishKill()
|
||||
await request
|
||||
|
||||
expect(killLog.log).toHaveBeenCalledWith('session-killed', {
|
||||
sessionId: 'agent-session',
|
||||
immediate: true,
|
||||
clientId: 'control-42'
|
||||
})
|
||||
})
|
||||
|
||||
it('attributes a failed kill without claiming the session was killed', async () => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'daemon-kill-attribution-'))
|
||||
const killLog = { log: vi.fn(), close: vi.fn() }
|
||||
server = new DaemonServer({
|
||||
socketPath: join(dir, 'daemon.sock'),
|
||||
tokenPath: join(dir, 'daemon.token'),
|
||||
log: killLog,
|
||||
spawnSubprocess: () => {
|
||||
throw new Error('not used')
|
||||
}
|
||||
})
|
||||
const daemon = server as unknown as DaemonServerPrivate
|
||||
vi.spyOn(daemon.host, 'kill').mockRejectedValue(new Error('kill refused'))
|
||||
|
||||
await expect(
|
||||
daemon.requestRouter.route('control-42', {
|
||||
id: 'kill-1',
|
||||
type: 'kill',
|
||||
payload: { sessionId: 'agent-session', immediate: true }
|
||||
})
|
||||
).rejects.toThrow('kill refused')
|
||||
|
||||
expect(killLog.log).toHaveBeenCalledWith('session-kill-failed', {
|
||||
sessionId: 'agent-session',
|
||||
immediate: true,
|
||||
clientId: 'control-42',
|
||||
errorName: 'Error',
|
||||
error: 'kill refused'
|
||||
})
|
||||
expect(killLog.log).not.toHaveBeenCalledWith('session-killed', expect.anything())
|
||||
})
|
||||
|
||||
it('attributes a tolerated kill after canceling a pending spawn', async () => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'daemon-kill-attribution-'))
|
||||
const killLog = { log: vi.fn(), close: vi.fn() }
|
||||
server = new DaemonServer({
|
||||
socketPath: join(dir, 'daemon.sock'),
|
||||
tokenPath: join(dir, 'daemon.token'),
|
||||
log: killLog,
|
||||
spawnSubprocess: () => {
|
||||
throw new Error('not used')
|
||||
}
|
||||
})
|
||||
const daemon = server as unknown as DaemonServerPrivate
|
||||
const pendingPreparation = {
|
||||
canceled: false,
|
||||
controller: new AbortController(),
|
||||
clientId: 'control-42'
|
||||
}
|
||||
daemon.preparations.pending.set('agent-session', new Set([pendingPreparation]))
|
||||
vi.spyOn(daemon.host, 'kill').mockRejectedValue(new SessionNotFoundError('agent-session'))
|
||||
|
||||
await daemon.requestRouter.route('control-42', {
|
||||
id: 'kill-1',
|
||||
type: 'kill',
|
||||
payload: { sessionId: 'agent-session', immediate: true }
|
||||
})
|
||||
|
||||
expect(pendingPreparation.canceled).toBe(true)
|
||||
expect(killLog.log).toHaveBeenCalledWith('session-killed', {
|
||||
sessionId: 'agent-session',
|
||||
immediate: true,
|
||||
clientId: 'control-42'
|
||||
})
|
||||
expect(killLog.log).not.toHaveBeenCalledWith('session-kill-failed', expect.anything())
|
||||
})
|
||||
})
|
||||
@@ -7,14 +7,11 @@ import {
|
||||
getSeveredDaemon,
|
||||
installSeveredDaemonController,
|
||||
noteSeveredDaemon,
|
||||
readSeveredDaemonStatus,
|
||||
restartSeveredDaemon
|
||||
} from './daemon-host-image-state'
|
||||
|
||||
import type { DaemonHostImageInspection } from './daemon-host-image'
|
||||
import {
|
||||
createSeveredDaemonController,
|
||||
hasSeveredDaemonBeenReplaced
|
||||
} from './daemon-severed-restart'
|
||||
import { createSeveredDaemonController } from './daemon-severed-restart'
|
||||
|
||||
const SEVERED: DaemonHostImageInspection = {
|
||||
verdict: 'severed',
|
||||
@@ -47,22 +44,6 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
describe('restarting a daemon whose AppImage files are gone', () => {
|
||||
it('counts every running terminal a restart would end, local fallback included', async () => {
|
||||
setUp(SEVERED, [{ isAlive: true }, { isAlive: false }, { isAlive: true }], 2)
|
||||
await expect(readSeveredDaemonStatus()).resolves.toEqual({ ...EXPECTED, liveSessionCount: 4 })
|
||||
})
|
||||
|
||||
it('restarts only the incarnation the caller saw, after re-reading it', async () => {
|
||||
const restart = setUp(SEVERED)
|
||||
await expect(restartSeveredDaemon(EXPECTED)).resolves.toEqual({
|
||||
status: 'restarted',
|
||||
killedCount: 1
|
||||
})
|
||||
// Pass the PID through so teardown can recheck endpoint ownership.
|
||||
expect(restart).toHaveBeenCalledWith(4288)
|
||||
expect(getSeveredDaemon()).toBeNull()
|
||||
})
|
||||
|
||||
it('refuses when the caller saw another incarnation', async () => {
|
||||
const restart = setUp(SEVERED)
|
||||
await expect(restartSeveredDaemon({ ...EXPECTED, linuxStartTicks: '1' })).resolves.toEqual({
|
||||
@@ -90,38 +71,4 @@ describe('restarting a daemon whose AppImage files are gone', () => {
|
||||
expect(restart).not.toHaveBeenCalled()
|
||||
expect(getSeveredDaemon()).toEqual(EXPECTED)
|
||||
})
|
||||
|
||||
it('reports nothing severed until a daemon was kept severed', async () => {
|
||||
setUp(SEVERED)
|
||||
clearSeveredDaemon()
|
||||
await expect(readSeveredDaemonStatus()).resolves.toBeNull()
|
||||
await expect(restartSeveredDaemon(EXPECTED)).resolves.toEqual({
|
||||
status: 'refused',
|
||||
reason: 'not-severed'
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasSeveredDaemonBeenReplaced', () => {
|
||||
it('keeps the quarantine while the severed incarnation still owns the endpoint', () => {
|
||||
setUp(SEVERED)
|
||||
expect(hasSeveredDaemonBeenReplaced('/pid', () => SEVERED)).toBe(false)
|
||||
expect(hasSeveredDaemonBeenReplaced('/pid', () => ({ ...SEVERED, verdict: 'unknown' }))).toBe(
|
||||
false
|
||||
)
|
||||
expect(getSeveredDaemon()).toEqual(EXPECTED)
|
||||
})
|
||||
|
||||
it('lifts it once a verified, intact daemon replaced the severed one', () => {
|
||||
setUp(SEVERED)
|
||||
expect(
|
||||
hasSeveredDaemonBeenReplaced('/pid', () => ({
|
||||
verdict: 'intact',
|
||||
pid: 9000,
|
||||
linuxStartTicks: '5',
|
||||
bootId: 'boot-1'
|
||||
}))
|
||||
).toBe(true)
|
||||
expect(getSeveredDaemon()).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -35,13 +35,6 @@ describe('readDaemonWslSleepCwd', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it("answers the shell's folder in the bridge's UNC spelling", async () => {
|
||||
readRows.mockResolvedValue([shell])
|
||||
expect(await readDaemonWslSleepCwd(pane)).toBe('\\\\wsl.localhost\\Ubuntu\\home\\a\\deep')
|
||||
// A live pane's distro is running: no separate running check.
|
||||
expect(readRows).toHaveBeenCalledWith('Ubuntu', 3_000, { running: true })
|
||||
})
|
||||
|
||||
it('gives the read at most a quarter of what is left of the Sleep, capped at 3 s', async () => {
|
||||
readRows.mockResolvedValue([shell])
|
||||
await readDaemonWslSleepCwd(pane, Date.now() + 4_000)
|
||||
@@ -51,14 +44,6 @@ describe('readDaemonWslSleepCwd', () => {
|
||||
expect(readRows).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('gives up at its budget when the distro does not answer', async () => {
|
||||
vi.useFakeTimers()
|
||||
readRows.mockReturnValue(new Promise(() => {}))
|
||||
const read = readDaemonWslSleepCwd(pane)
|
||||
await vi.advanceTimersByTimeAsync(3_000)
|
||||
expect(await read).toBeNull()
|
||||
})
|
||||
|
||||
it("answers quit's panes within its own budget, leaving out panes it cannot read", async () => {
|
||||
readRows.mockResolvedValue([shell])
|
||||
const cwds = await readDaemonWslQuitCwds(
|
||||
@@ -90,10 +75,4 @@ describe('readDaemonWslSleepCwd', () => {
|
||||
await vi.advanceTimersByTimeAsync(3_000)
|
||||
expect(await read).toMatchObject({ cwd: null, rows: null, shells: null, timedOut: true })
|
||||
})
|
||||
|
||||
it('reads nothing off Windows', async () => {
|
||||
Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' })
|
||||
expect(await readDaemonWslSleepCwd(pane)).toBeNull()
|
||||
expect(readRows).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -28,20 +28,6 @@ describe('PostReadyFlushGate', () => {
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('does not flush immediately when armed', () => {
|
||||
gate.arm()
|
||||
expect(onFlush).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('flushes via short delay after notifyData signals the prompt draw', () => {
|
||||
gate.arm()
|
||||
gate.notifyData()
|
||||
expect(onFlush).not.toHaveBeenCalled()
|
||||
|
||||
vi.advanceTimersByTime(POST_READY_FLUSH_DELAY_MS)
|
||||
expect(onFlush).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('flushes via short delay when arm receives post-marker bytes evidence', () => {
|
||||
gate.arm(true)
|
||||
vi.advanceTimersByTime(POST_READY_FLUSH_DELAY_MS - 1)
|
||||
@@ -51,27 +37,6 @@ describe('PostReadyFlushGate', () => {
|
||||
expect(onFlush).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('flushes via wall-clock fallback when no notifyData arrives', () => {
|
||||
gate.arm()
|
||||
|
||||
vi.advanceTimersByTime(POST_READY_FLUSH_FALLBACK_MS)
|
||||
expect(onFlush).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('does not fallback at the old duplicate-echo race window', () => {
|
||||
gate.arm()
|
||||
|
||||
vi.advanceTimersByTime(50)
|
||||
|
||||
expect(onFlush).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ignores notifyData before arm()', () => {
|
||||
gate.notifyData()
|
||||
vi.advanceTimersByTime(1000)
|
||||
expect(onFlush).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('notifyData after the fallback fired is a no-op', () => {
|
||||
gate.arm()
|
||||
vi.advanceTimersByTime(POST_READY_FLUSH_FALLBACK_MS)
|
||||
@@ -82,16 +47,6 @@ describe('PostReadyFlushGate', () => {
|
||||
expect(onFlush).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('only the first notifyData schedules the short-delay flush', () => {
|
||||
gate.arm()
|
||||
gate.notifyData()
|
||||
gate.notifyData()
|
||||
gate.notifyData()
|
||||
|
||||
vi.advanceTimersByTime(POST_READY_FLUSH_DELAY_MS)
|
||||
expect(onFlush).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('clear() cancels a pending fallback flush', () => {
|
||||
gate.arm()
|
||||
gate.clear()
|
||||
|
||||
@@ -126,14 +126,6 @@ describe('process boundary ground at a cold restore', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('grounds without moving the cursor', () => {
|
||||
const live = emulator(DAEMON_SESSION_SCROLLBACK_ROWS)
|
||||
write(live, 'OLD_OUTPUT_1\r\n$ ')
|
||||
write(live, PROCESS_BOUNDARY_GROUND)
|
||||
write(live, 'X')
|
||||
expect(live.getBufferTailLines(24)[1]).toBe('$ X')
|
||||
})
|
||||
|
||||
// awin verify-11: a reattach after Wake showed the new prompt beside the dead shell's (`$ $`).
|
||||
it("starts the new shell's prompt on its own line, keeping the recovered history", () => {
|
||||
const live = seededLive(checkpointOfDeadProcess(''))
|
||||
|
||||
@@ -103,36 +103,4 @@ describe('#7329 remote-server snapshot corruption', () => {
|
||||
term.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not eat the continuation byte when the tail and continuation are contiguous', async () => {
|
||||
// Test a contiguous continuation directly; production snapshot-sequence accounting is not exercised here.
|
||||
const emu = new HeadlessEmulator({ cols: 80, rows: 24 })
|
||||
const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true })
|
||||
try {
|
||||
await emulatorWrite(emu, '\x1b[38;5;')
|
||||
const snapshot = emu.getSnapshot({ scrollbackRows: 0 })
|
||||
expect(snapshot.pendingEscapeTailAnsi).toBe('\x1b[38;5;')
|
||||
await replayRemoteSnapshot(term, snapshot)
|
||||
await writeXterm(term, '82mHELLO')
|
||||
const visible = renderVisible(term)
|
||||
expect(visible).toBe('HELLO')
|
||||
} finally {
|
||||
emu.dispose()
|
||||
term.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('documents the residual edge: an idle-death tail eats the next output byte', async () => {
|
||||
// A tail with no continuation can consume unrelated later output; pin the known parser limitation.
|
||||
const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true })
|
||||
try {
|
||||
await writeXterm(term, 'prompt$ ')
|
||||
await writeXterm(term, '\x1b[3')
|
||||
await writeXterm(term, 'yes\r\n')
|
||||
// CSI consumes 'y' as a final byte; only the remaining 'es' renders.
|
||||
expect(renderVisible(term)).toBe('prompt$ es')
|
||||
} finally {
|
||||
term.dispose()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -63,19 +63,6 @@ describe('Session pending output', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('coalesces adjacent output chunks', () => {
|
||||
const subprocess = createMockSubprocess()
|
||||
const live = createSession(subprocess)
|
||||
|
||||
for (let i = 0; i < 100; i += 1) {
|
||||
subprocess.simulateData(`chunk-${i};`)
|
||||
}
|
||||
|
||||
const take = live.takePendingOutput(false)
|
||||
expect(take!.records).toHaveLength(1)
|
||||
expect(take!.records[0]).toMatchObject({ kind: 'output' })
|
||||
})
|
||||
|
||||
it('drains on take and increments the batch sequence', () => {
|
||||
const subprocess = createMockSubprocess()
|
||||
const live = createSession(subprocess)
|
||||
@@ -125,10 +112,4 @@ describe('Session pending output', () => {
|
||||
const next = live.takePendingOutput(false)
|
||||
expect(next!.records).toEqual([])
|
||||
})
|
||||
|
||||
it('returns null after dispose', () => {
|
||||
const live = createSession()
|
||||
live.dispose()
|
||||
expect(live.takePendingOutput(false)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,11 +2,7 @@ import { describe, expect, it } from 'vitest'
|
||||
import { HeadlessEmulator } from './headless-emulator'
|
||||
import { buildRehydrateSequences } from './terminal-mode-rehydrate-sequences'
|
||||
import { getRecoveredHistorySeedSegments } from './terminal-history-seed-segments'
|
||||
import {
|
||||
PROCESS_BOUNDARY_GROUND,
|
||||
RESET_GRAPHIC_RENDITION
|
||||
} from '../../shared/terminal-mode-reset-profiles'
|
||||
import { buildFreshShellViewportBlankingSequence } from '../../shared/terminal-fresh-shell-viewport'
|
||||
|
||||
import type { ColdRestoreInfo } from './terminal-history-cold-restore-info'
|
||||
import type { TerminalModes } from './types'
|
||||
|
||||
@@ -19,10 +15,6 @@ const ARMED_MODES: TerminalModes = {
|
||||
alternateScreen: false
|
||||
}
|
||||
|
||||
// Assert seed placement here; terminal-mode-reset-profiles.test.ts pins the reset bytes.
|
||||
const GROUND = PROCESS_BOUNDARY_GROUND
|
||||
const FRESH_VIEWPORT = buildFreshShellViewportBlankingSequence(24)
|
||||
|
||||
function restoreInfo(overrides: Partial<ColdRestoreInfo> = {}): ColdRestoreInfo {
|
||||
return {
|
||||
snapshotAnsi: 'user@host ~ $ \x1b[?1003h',
|
||||
@@ -37,51 +29,6 @@ function restoreInfo(overrides: Partial<ColdRestoreInfo> = {}): ColdRestoreInfo
|
||||
}
|
||||
|
||||
describe('getRecoveredHistorySeedSegments', () => {
|
||||
it('grounds after the snapshot and drops the dead process torn escape tail', () => {
|
||||
const segments = getRecoveredHistorySeedSegments(
|
||||
restoreInfo({ pendingEscapeTailAnsi: '\x1b[3' })
|
||||
)
|
||||
expect(segments).toEqual([
|
||||
`${RESET_GRAPHIC_RENDITION}\x1b[?1003h\x1b[?1006h`,
|
||||
'user@host ~ $ \x1b[?1003h',
|
||||
GROUND,
|
||||
FRESH_VIEWPORT
|
||||
])
|
||||
})
|
||||
|
||||
it('grounds the alt-screen normal-buffer branch too', () => {
|
||||
expect(
|
||||
getRecoveredHistorySeedSegments(
|
||||
restoreInfo({ modes: { ...ARMED_MODES, alternateScreen: true } })
|
||||
)
|
||||
).toEqual([`${RESET_GRAPHIC_RENDITION}user@host ~ $ `, GROUND, FRESH_VIEWPORT])
|
||||
})
|
||||
|
||||
it('stays empty when there is no recovered normal buffer', () => {
|
||||
expect(
|
||||
getRecoveredHistorySeedSegments(
|
||||
restoreInfo({
|
||||
modes: { ...ARMED_MODES, alternateScreen: true },
|
||||
scrollbackAnsi: '',
|
||||
snapshotAnsi: ''
|
||||
})
|
||||
)
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps the empty "nothing to recover" sentinel on the normal-screen branch', () => {
|
||||
expect(
|
||||
getRecoveredHistorySeedSegments(
|
||||
restoreInfo({
|
||||
modes: { ...ARMED_MODES, mouseTracking: false, mouseTrackingMode: 'none' },
|
||||
scrollbackAnsi: '',
|
||||
snapshotAnsi: '',
|
||||
rehydrateSequences: ''
|
||||
})
|
||||
)
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('recovers nothing when a torn escape is the only recovered data', () => {
|
||||
expect(
|
||||
getRecoveredHistorySeedSegments(
|
||||
@@ -112,15 +59,4 @@ describe('getRecoveredHistorySeedSegments', () => {
|
||||
emulator.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not touch the live-session reattach payload (mobile scroll gestures)', () => {
|
||||
// Live reattach must preserve the active TUI’s modes; only recovery knows that process is dead.
|
||||
expect(buildRehydrateSequences(ARMED_MODES)).toBe('\x1b[?1003h\x1b[?1006h')
|
||||
})
|
||||
|
||||
it('grounds the pen before re-entering the alternate screen', () => {
|
||||
expect(buildRehydrateSequences({ ...ARMED_MODES, alternateScreen: true })).toBe(
|
||||
`${RESET_GRAPHIC_RENDITION}\x1b[?1049h\x1b[?1003h\x1b[?1006h`
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -8,7 +8,6 @@ import { serializeWithAbsoluteCursor } from '../../shared/terminal-serialize-abs
|
||||
import { readTerminalMouseEncoding } from '../../shared/terminal-mouse-encoding'
|
||||
|
||||
const CODEX_FULLSCREEN_MODES = '\x1b[?1049h\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h'
|
||||
const X10_WHEEL_UP_AT_10_5 = `\x1b[M${String.fromCharCode(96, 42, 37)}`
|
||||
const SGR_WHEEL_UP_AT_10_5 = '\x1b[<64;10;5M'
|
||||
|
||||
function createTerminal(): { terminal: Terminal; addon: SerializeAddon } {
|
||||
@@ -69,16 +68,6 @@ function wheelUpReport(terminal: Terminal): string | null {
|
||||
}
|
||||
|
||||
describe('snapshot mouse encoding', () => {
|
||||
it('the bare addon drops SGR encoding, so its restore reports X10 (the #23818 shape)', async () => {
|
||||
const { terminal, addon } = createTerminal()
|
||||
await write(terminal, `shell$ ${CODEX_FULLSCREEN_MODES}codex`)
|
||||
|
||||
const restored = await replay(addon.serialize())
|
||||
|
||||
expect(restored.modes.mouseTrackingMode).toBe('any')
|
||||
expect(wheelUpReport(restored)).toBe(X10_WHEEL_UP_AT_10_5)
|
||||
})
|
||||
|
||||
it('round-trips SGR encoding with the tracking mode, so the restore reports SGR', async () => {
|
||||
const { terminal, addon } = createTerminal()
|
||||
await write(terminal, `shell$ ${CODEX_FULLSCREEN_MODES}codex`)
|
||||
@@ -111,19 +100,6 @@ describe('snapshot mouse encoding', () => {
|
||||
expect(wheelUpReport(restored)).toBeNull()
|
||||
})
|
||||
|
||||
it('adds nothing for the default encoding or when modes are excluded', async () => {
|
||||
const { terminal, addon } = createTerminal()
|
||||
await write(terminal, 'x\x1b[?1000h')
|
||||
const legacy = serializeWithAbsoluteCursor(addon, terminal)
|
||||
expect(legacy).toContain('\x1b[?1000h')
|
||||
expect(legacy).not.toContain('\x1b[?1006h')
|
||||
expect(legacy).not.toContain('\x1b[?1016h')
|
||||
|
||||
await write(terminal, '\x1b[?1006h')
|
||||
const excluded = serializeWithAbsoluteCursor(addon, terminal, { excludeModes: true })
|
||||
expect(excluded).not.toContain('\x1b[?1006h')
|
||||
})
|
||||
|
||||
it('carries the encoding from a renderer snapshot through a headless seed to its snapshot', async () => {
|
||||
// Mobile replay discards bytes before the last alternate-screen entry; encoding must survive that slice.
|
||||
const { terminal, addon } = createTerminal()
|
||||
@@ -142,16 +118,4 @@ describe('snapshot mouse encoding', () => {
|
||||
expect(wheelUpReport(await replay(data))).toBe(SGR_WHEEL_UP_AT_10_5)
|
||||
emulator.dispose()
|
||||
})
|
||||
|
||||
it('a snapshot from an older host without the encoding restores as before', async () => {
|
||||
const emulator = new HeadlessEmulator({ cols: 40, rows: 10 })
|
||||
await emulator.write('\x1b[?1049h\x1b[?1003hcodex')
|
||||
|
||||
const snapshot = emulator.getSnapshot()
|
||||
|
||||
expect(snapshot.modes.mouseTrackingMode).toBe('any')
|
||||
expect(snapshot.modes.sgrMouseMode).toBe(false)
|
||||
expect(snapshot.rehydrateSequences).not.toContain('\x1b[?1006h')
|
||||
emulator.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { inspectEmulatorAvailability } from './emulator-availability'
|
||||
import type { EmulatorBridge } from './emulator-bridge'
|
||||
import type { SimulatorDevice } from './simctl-simulator-devices'
|
||||
import type { BackendAvailability } from './backends/emulator-backend'
|
||||
import { EmulatorError } from './emulator-errors'
|
||||
import { emulatorFailureText } from '../../shared/emulator-failure-copy'
|
||||
|
||||
type FakeBridgeOverrides = {
|
||||
supported?: boolean
|
||||
listSimulators?: () => Promise<SimulatorDevice[]>
|
||||
checkServeSimAvailable?: () => Promise<void>
|
||||
android?: BackendAvailability
|
||||
}
|
||||
|
||||
const NO_ANDROID: BackendAvailability = {
|
||||
available: false,
|
||||
devices: [],
|
||||
message: 'Android SDK not found. Install Android Studio and set ANDROID_HOME.'
|
||||
}
|
||||
|
||||
function fakeBridge(overrides: FakeBridgeOverrides = {}): EmulatorBridge {
|
||||
const android = overrides.android ?? NO_ANDROID
|
||||
return {
|
||||
listBackends: () => [
|
||||
{ kind: 'ios', isSupportedOnHost: () => overrides.supported ?? true },
|
||||
{
|
||||
kind: 'android',
|
||||
isSupportedOnHost: () => android.available,
|
||||
checkAvailability: async () => android
|
||||
}
|
||||
],
|
||||
listSimulators: overrides.listSimulators ?? (async () => []),
|
||||
checkServeSimAvailable: overrides.checkServeSimAvailable ?? (async () => {})
|
||||
} as unknown as EmulatorBridge
|
||||
}
|
||||
|
||||
const DEVICE: SimulatorDevice = {
|
||||
name: 'iPhone 17 Pro',
|
||||
udid: 'udid-1',
|
||||
state: 'Booted',
|
||||
runtime: 'com.apple.CoreSimulator.SimRuntime.iOS-18-0'
|
||||
}
|
||||
|
||||
describe('inspectEmulatorAvailability', () => {
|
||||
it('falls back to the Android setup message when no backend is available', async () => {
|
||||
const result = await inspectEmulatorAvailability(fakeBridge({ supported: false }))
|
||||
expect(result.available).toBe(false)
|
||||
expect(result.message).toMatch(/Android SDK/)
|
||||
expect(result.devices).toEqual([])
|
||||
})
|
||||
|
||||
it('reports ready when iOS simulators exist and serve-sim is available', async () => {
|
||||
const result = await inspectEmulatorAvailability(
|
||||
fakeBridge({ supported: true, listSimulators: async () => [DEVICE] })
|
||||
)
|
||||
expect(result.available).toBe(true)
|
||||
expect(result.message).toBe('Ready')
|
||||
expect(result.devices).toEqual([DEVICE])
|
||||
})
|
||||
|
||||
it('reports ready with Android devices when the iOS backend is unsupported', async () => {
|
||||
const result = await inspectEmulatorAvailability(
|
||||
fakeBridge({
|
||||
supported: false,
|
||||
android: {
|
||||
available: true,
|
||||
message: 'Ready',
|
||||
devices: [
|
||||
{
|
||||
backend: 'android',
|
||||
id: 'emulator-5554',
|
||||
name: 'Pixel_7',
|
||||
state: 'booted',
|
||||
isAvailable: true
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
)
|
||||
expect(result.available).toBe(true)
|
||||
expect(result.message).toBe('Ready')
|
||||
expect(result.devices).toEqual([
|
||||
{
|
||||
name: 'Pixel_7',
|
||||
udid: 'emulator-5554',
|
||||
state: 'Booted',
|
||||
runtime: 'Android',
|
||||
isAvailable: true
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('flags simctl when no simulators are installed', async () => {
|
||||
const result = await inspectEmulatorAvailability(
|
||||
fakeBridge({ supported: true, listSimulators: async () => [] })
|
||||
)
|
||||
expect(result.available).toBe(false)
|
||||
expect(result.simctl.ok).toBe(false)
|
||||
expect(result.simctl.message).toMatch(/No iOS simulators/)
|
||||
})
|
||||
|
||||
it('flags serve-sim when its check throws', async () => {
|
||||
const result = await inspectEmulatorAvailability(
|
||||
fakeBridge({
|
||||
supported: true,
|
||||
listSimulators: async () => [DEVICE],
|
||||
checkServeSimAvailable: async () => {
|
||||
throw new Error('serve-sim missing')
|
||||
}
|
||||
})
|
||||
)
|
||||
expect(result.available).toBe(false)
|
||||
expect(result.serveSim.ok).toBe(false)
|
||||
expect(result.serveSim.message).toBe('serve-sim missing')
|
||||
})
|
||||
|
||||
it('flags simctl when listing simulators throws', async () => {
|
||||
const result = await inspectEmulatorAvailability(
|
||||
fakeBridge({
|
||||
supported: true,
|
||||
listSimulators: async () => {
|
||||
throw new Error('xcrun exploded')
|
||||
}
|
||||
})
|
||||
)
|
||||
expect(result.available).toBe(false)
|
||||
expect(result.simctl.ok).toBe(false)
|
||||
expect(result.simctl.message).toBe('xcrun exploded')
|
||||
})
|
||||
|
||||
it('codes known setup sentences without changing their English text', async () => {
|
||||
const result = await inspectEmulatorAvailability(
|
||||
fakeBridge({
|
||||
supported: true,
|
||||
listSimulators: async () => {
|
||||
throw new EmulatorError(
|
||||
'emulator_device_not_found',
|
||||
emulatorFailureText('simulatorNotFound', { udid: 'udid-9' })
|
||||
)
|
||||
},
|
||||
android: {
|
||||
available: false,
|
||||
devices: [],
|
||||
message: 'adb exploded',
|
||||
messageCode: 'adbUnavailable'
|
||||
}
|
||||
})
|
||||
)
|
||||
expect(result.simctl).toEqual({
|
||||
ok: false,
|
||||
message:
|
||||
'Simulator udid-9 not found. Create one via Xcode > Window > Devices and Simulators.',
|
||||
messageCode: 'simulatorNotFound',
|
||||
messageParams: { udid: 'udid-9' }
|
||||
})
|
||||
expect(result.android).toMatchObject({ message: 'adb exploded', messageCode: 'adbUnavailable' })
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,5 @@
|
||||
import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
|
||||
import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
|
||||
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
@@ -43,25 +44,6 @@ afterEach(async () => {
|
||||
})
|
||||
|
||||
describe('packed-refs lock ownership', () => {
|
||||
it('claims a repository with no lock and records the owner', async () => {
|
||||
const commonDir = await gitCommonDir()
|
||||
const { marker } = paths(commonDir)
|
||||
|
||||
await expect(new PackRefsLockOwnership(commonDir).claim()).resolves.toEqual({ ok: true })
|
||||
|
||||
await expect(readFile(marker, 'utf-8')).resolves.toContain(String(process.pid))
|
||||
})
|
||||
|
||||
it('drops the owner marker on release', async () => {
|
||||
const commonDir = await gitCommonDir()
|
||||
const ownership = new PackRefsLockOwnership(commonDir)
|
||||
await ownership.claim()
|
||||
|
||||
await ownership.release()
|
||||
|
||||
await expect(exists(paths(commonDir).marker)).resolves.toBe(false)
|
||||
})
|
||||
|
||||
it('refuses a lock it cannot prove is its own', async () => {
|
||||
const commonDir = await gitCommonDir()
|
||||
await writeFile(paths(commonDir).lock, 'someone else')
|
||||
@@ -70,18 +52,6 @@ describe('packed-refs lock ownership', () => {
|
||||
await expect(exists(paths(commonDir).lock)).resolves.toBe(true)
|
||||
})
|
||||
|
||||
it('refuses a lock whose recorded owner is still running', async () => {
|
||||
const commonDir = await gitCommonDir()
|
||||
const { lock, marker } = paths(commonDir)
|
||||
await writeFile(lock, 'in progress')
|
||||
await writeFile(marker, JSON.stringify({ pid: process.pid }))
|
||||
|
||||
await expect(
|
||||
new PackRefsLockOwnership(commonDir).claim(laterBy(ABANDONED_LOCK_AGE_MS + 1))
|
||||
).resolves.toMatchObject({ ok: false })
|
||||
await expect(exists(lock)).resolves.toBe(true)
|
||||
})
|
||||
|
||||
it('reclaims the lock its own dead process left behind', async () => {
|
||||
const commonDir = await gitCommonDir()
|
||||
const { lock, marker } = paths(commonDir)
|
||||
@@ -136,27 +106,4 @@ describe('packed-refs lock ownership', () => {
|
||||
).resolves.toMatchObject({ ok: false })
|
||||
await expect(exists(lock)).resolves.toBe(true)
|
||||
})
|
||||
|
||||
it('claims cleanly when a marker outlived its lock', async () => {
|
||||
const commonDir = await gitCommonDir()
|
||||
await writeFile(paths(commonDir).marker, JSON.stringify({ pid: DEAD_PID }))
|
||||
|
||||
await expect(new PackRefsLockOwnership(commonDir).claim()).resolves.toEqual({ ok: true })
|
||||
})
|
||||
})
|
||||
|
||||
describe('unattributed per-ref locks', () => {
|
||||
it('preserves empty ref locks when only an old dead-owner marker exists', async () => {
|
||||
const commonDir = await gitCommonDir()
|
||||
const namespace = join(commonDir, 'refs', 'remotes', 'origin')
|
||||
await mkdir(namespace, { recursive: true })
|
||||
await writeFile(join(namespace, 'main.lock'), '')
|
||||
await writeFile(join(namespace, 'main'), 'a'.repeat(40))
|
||||
await writeFile(paths(commonDir).marker, JSON.stringify({ pid: DEAD_PID }))
|
||||
|
||||
await new PackRefsLockOwnership(commonDir).claim(laterBy(ABANDONED_LOCK_AGE_MS + 1))
|
||||
|
||||
await expect(exists(join(namespace, 'main.lock'))).resolves.toBe(true)
|
||||
await expect(exists(join(namespace, 'main'))).resolves.toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -34,20 +34,6 @@ describe('remote ref probe cache (P1-D)', () => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('answers concurrent lookups for one repo with a single probe', async () => {
|
||||
const cache = createRemoteRefProbeCache(parseExampleRef)
|
||||
gitExecFileAsyncMock.mockResolvedValue({ stdout: 'git@example.com:team/repo.git\n' })
|
||||
|
||||
const answers = await Promise.all([
|
||||
cache.get('/repo', 'origin'),
|
||||
cache.get('/repo', 'origin'),
|
||||
cache.get('/repo', 'origin')
|
||||
])
|
||||
|
||||
expect(answers).toEqual([{ repo: 'team/repo' }, { repo: 'team/repo' }, { repo: 'team/repo' }])
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('re-probes a repo whose remotes could have changed since the miss', async () => {
|
||||
const cache = createRemoteRefProbeCache(parseExampleRef)
|
||||
gitExecFileAsyncMock.mockRejectedValueOnce(new Error("fatal: No such remote 'origin'"))
|
||||
@@ -64,17 +50,6 @@ describe('remote ref probe cache (P1-D)', () => {
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('keeps a resolved ref without re-probing', async () => {
|
||||
const cache = createRemoteRefProbeCache(parseExampleRef)
|
||||
gitExecFileAsyncMock.mockResolvedValue({ stdout: 'git@example.com:team/repo.git\n' })
|
||||
|
||||
await expect(cache.get('/repo', 'origin')).resolves.toEqual({ repo: 'team/repo' })
|
||||
vi.setSystemTime(1_000_000 + NEGATIVE_ENTRY_TTL_MS * 10)
|
||||
await expect(cache.get('/repo', 'origin')).resolves.toEqual({ repo: 'team/repo' })
|
||||
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('does not let a probe abandoned as stale overwrite its successor answer', async () => {
|
||||
const cache = createRemoteRefProbeCache(parseExampleRef)
|
||||
const stalled = deferred<{ stdout: string }>()
|
||||
@@ -94,19 +69,6 @@ describe('remote ref probe cache (P1-D)', () => {
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('holds a parsed-as-not-mine remote for the negative interval, then re-asks', async () => {
|
||||
const cache = createRemoteRefProbeCache(parseExampleRef)
|
||||
gitExecFileAsyncMock.mockResolvedValue({ stdout: 'git@elsewhere.example:team/repo.git\n' })
|
||||
|
||||
await expect(cache.get('/repo', 'origin')).resolves.toBeNull()
|
||||
await expect(cache.get('/repo', 'origin')).resolves.toBeNull()
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1)
|
||||
|
||||
vi.setSystemTime(1_000_000 + NEGATIVE_ENTRY_TTL_MS + 1)
|
||||
await expect(cache.get('/repo', 'origin')).resolves.toBeNull()
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('answers an SSH repo with null without running git on this machine', async () => {
|
||||
const cache = createRemoteRefProbeCache(parseExampleRef)
|
||||
|
||||
|
||||
@@ -49,31 +49,6 @@ describe('assertWorktreeCleanForRemoval', () => {
|
||||
.mockRejectedValue(new Error('git ls-files exited with code 128'))
|
||||
})
|
||||
|
||||
it('returns without checking git status for force removals', async () => {
|
||||
await expect(assertWorktreeCleanForRemoval('/repo-feature', true)).resolves.toBeUndefined()
|
||||
expect(gitExecFileAsyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('passes when git status output is empty', async () => {
|
||||
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
|
||||
await expect(assertWorktreeCleanForRemoval('/repo-feature')).resolves.toBeUndefined()
|
||||
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledWith(
|
||||
['status', '--porcelain', '--untracked-files=all', '--ignore-submodules=none'],
|
||||
{ cwd: '/repo-feature', timeout: WORKTREE_REMOVAL_PREFLIGHT_TIMEOUT_MS }
|
||||
)
|
||||
})
|
||||
|
||||
it('throws a dedicated dirty/untracked error when status output is non-empty', async () => {
|
||||
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '?? scratch.txt\n', stderr: '' })
|
||||
|
||||
await expect(assertWorktreeCleanForRemoval('/repo-feature')).rejects.toMatchObject({
|
||||
message: 'Worktree has uncommitted or untracked changes.',
|
||||
stdout: '?? scratch.txt\n'
|
||||
})
|
||||
})
|
||||
|
||||
it('ignores configured linked paths without mutating them before preflight', async () => {
|
||||
gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '?? node_modules\0', stderr: '' })
|
||||
|
||||
@@ -89,19 +64,6 @@ describe('assertWorktreeCleanForRemoval', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('allows a shorter caller deadline for destructive preflight', async () => {
|
||||
gitExecFileAsyncMock.mockRejectedValueOnce(new Error('git timed out.'))
|
||||
|
||||
await expect(
|
||||
assertWorktreeCleanForRemoval('/repo-feature', false, { timeout: 25 })
|
||||
).rejects.toThrow('git timed out.')
|
||||
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledWith(
|
||||
['status', '--porcelain', '--untracked-files=all', '--ignore-submodules=none'],
|
||||
{ cwd: '/repo-feature', timeout: 25 }
|
||||
)
|
||||
})
|
||||
|
||||
it('still rejects real changes when configured linked paths are ignored', async () => {
|
||||
gitExecFileAsyncMock.mockResolvedValueOnce({
|
||||
stdout: '?? node_modules\0 M src/index.ts\0',
|
||||
@@ -114,13 +76,4 @@ describe('assertWorktreeCleanForRemoval', () => {
|
||||
})
|
||||
).rejects.toMatchObject({ message: 'Worktree has uncommitted or untracked changes.' })
|
||||
})
|
||||
|
||||
it('rethrows preflight subprocess failures as-is', async () => {
|
||||
const error = Object.assign(new Error('fatal: not a git repository'), {
|
||||
stderr: 'fatal: not a git repository (or any of the parent directories): .git\n'
|
||||
})
|
||||
gitExecFileAsyncMock.mockRejectedValueOnce(error)
|
||||
|
||||
await expect(assertWorktreeCleanForRemoval('/repo-feature')).rejects.toBe(error)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -167,24 +167,6 @@ describe('branch line total against a real repository', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('counts an untracked-only branch from the untracked file contents', async () => {
|
||||
const repo = await createFixtureRepo()
|
||||
await write(repo, 'kept.txt', 'a\n')
|
||||
const mergeBase = commitAll(repo, 'base')
|
||||
await write(repo, 'src/new.ts', 'one\ntwo\nthree\n')
|
||||
|
||||
const result = await getStatus(repo, { branchLineTotalMergeBase: mergeBase })
|
||||
|
||||
expect(result.entries.map((entry) => entry.area)).toEqual(['untracked'])
|
||||
expect(result.branchLineTotal).toEqual({
|
||||
added: 3,
|
||||
removed: 0,
|
||||
mergeBase,
|
||||
test: NO_LINES,
|
||||
generated: NO_LINES
|
||||
})
|
||||
})
|
||||
|
||||
it('excludes a binary-only change, matching numstat reporting it as "-"', async () => {
|
||||
const repo = await createFixtureRepo()
|
||||
await write(repo, 'blob.bin', Buffer.from([0, 1, 2, 3, 10, 65, 66]))
|
||||
@@ -203,23 +185,6 @@ describe('branch line total against a real repository', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('contributes nothing for a pure rename', async () => {
|
||||
const repo = await createFixtureRepo()
|
||||
await write(repo, 'f.txt', 'a\nb\nc\nd\n')
|
||||
const mergeBase = commitAll(repo, 'base')
|
||||
git(repo, ['mv', 'f.txt', 'g.txt'])
|
||||
|
||||
const result = await getStatus(repo, { branchLineTotalMergeBase: mergeBase })
|
||||
|
||||
expect(result.branchLineTotal).toEqual({
|
||||
added: 0,
|
||||
removed: 0,
|
||||
mergeBase,
|
||||
test: NO_LINES,
|
||||
generated: NO_LINES
|
||||
})
|
||||
})
|
||||
|
||||
it('splits test-path and generated files out of the published total', async () => {
|
||||
const repo = await createFixtureRepo()
|
||||
await write(repo, 'src/a.ts', 'a\n')
|
||||
|
||||
@@ -1,27 +1,12 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const gitExecFileAsync = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('./runner', () => ({ gitExecFileAsync }))
|
||||
|
||||
import { hasLocalWorktreeBaseRef, probeWorktreeBaseRefPresence } from './worktree-base-ref-probe'
|
||||
import { probeWorktreeBaseRefPresence } from './worktree-base-ref-probe'
|
||||
|
||||
describe('probeWorktreeBaseRefPresence', () => {
|
||||
it('uses an exact show-ref probe and reports a present ref', async () => {
|
||||
const runGit = vi.fn().mockResolvedValue({ stdout: '' })
|
||||
|
||||
await expect(probeWorktreeBaseRefPresence(runGit, 'refs/heads/release/2026')).resolves.toBe(
|
||||
'present'
|
||||
)
|
||||
expect(runGit).toHaveBeenCalledWith([
|
||||
'show-ref',
|
||||
'--verify',
|
||||
'--quiet',
|
||||
'--',
|
||||
'refs/heads/release/2026'
|
||||
])
|
||||
})
|
||||
|
||||
it('treats show-ref exit 1 as an absent ref', async () => {
|
||||
const runGit = vi.fn().mockRejectedValue(Object.assign(new Error('missing ref'), { code: 1 }))
|
||||
|
||||
@@ -30,16 +15,6 @@ describe('probeWorktreeBaseRefPresence', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps repository and transport failures inconclusive', async () => {
|
||||
const runGit = vi
|
||||
.fn()
|
||||
.mockRejectedValue(Object.assign(new Error('not a git repository'), { code: 128 }))
|
||||
|
||||
await expect(probeWorktreeBaseRefPresence(runGit, 'refs/heads/release/2026')).resolves.toBe(
|
||||
'unknown'
|
||||
)
|
||||
})
|
||||
|
||||
it('does not treat a string transport code as a missing ref', async () => {
|
||||
const runGit = vi
|
||||
.fn()
|
||||
@@ -57,47 +32,3 @@ describe('probeWorktreeBaseRefPresence', () => {
|
||||
expect(runGit).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasLocalWorktreeBaseRef', () => {
|
||||
const repoPath = String.raw`C:\workspace\repo`
|
||||
|
||||
function resolveOnly(present: string[]): void {
|
||||
gitExecFileAsync.mockImplementation(async (args: string[]) => ({
|
||||
stdout: present.includes(args.at(-1)?.replace('^{commit}', '') ?? '') ? 'f'.repeat(40) : '',
|
||||
stderr: ''
|
||||
}))
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
gitExecFileAsync.mockReset()
|
||||
})
|
||||
|
||||
it('prefers the remote namespace for a slashed short name', async () => {
|
||||
resolveOnly(['refs/remotes/origin/main'])
|
||||
|
||||
await expect(hasLocalWorktreeBaseRef(repoPath, 'origin/main')).resolves.toBe(true)
|
||||
expect(gitExecFileAsync).toHaveBeenCalledWith(
|
||||
['rev-parse', '--verify', '--quiet', 'refs/remotes/origin/main^{commit}'],
|
||||
{ cwd: repoPath }
|
||||
)
|
||||
})
|
||||
|
||||
it('probes a bare commit id as an object, not as a ref', async () => {
|
||||
const sha = 'a'.repeat(40)
|
||||
resolveOnly([sha])
|
||||
|
||||
await expect(hasLocalWorktreeBaseRef(repoPath, sha, { wslDistro: 'Ubuntu' })).resolves.toBe(
|
||||
true
|
||||
)
|
||||
expect(gitExecFileAsync).toHaveBeenCalledWith(
|
||||
['rev-parse', '--verify', '--quiet', `${sha}^{commit}`],
|
||||
{ cwd: repoPath, wslDistro: 'Ubuntu' }
|
||||
)
|
||||
})
|
||||
|
||||
it('reports a base no namespace resolves as absent', async () => {
|
||||
resolveOnly([])
|
||||
|
||||
await expect(hasLocalWorktreeBaseRef(repoPath, 'feature/topic')).resolves.toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,15 +3,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
const { gitExecFileAsyncMock } = vi.hoisted(() => ({ gitExecFileAsyncMock: vi.fn() }))
|
||||
vi.mock('../git/runner', () => ({ gitExecFileAsync: gitExecFileAsyncMock }))
|
||||
|
||||
import {
|
||||
githubPullRequestHeadLocalRef,
|
||||
reviewHeadRemoteRefComponent,
|
||||
REVIEW_HEAD_FETCH_TIMEOUT_MS
|
||||
} from '../../shared/review-head-tracking-ref'
|
||||
import { fetchGitHubPullRequestHeadRef, fetchPrHeadTrackingRef } from './pr-head-tracking-ref'
|
||||
|
||||
const ORIGIN_URL = 'https://github.com/acme/widgets.git'
|
||||
const ORIGIN_COMPONENT = reviewHeadRemoteRefComponent('origin', ORIGIN_URL)
|
||||
|
||||
describe('fetchPrHeadTrackingRef', () => {
|
||||
beforeEach(() => {
|
||||
@@ -24,22 +18,6 @@ describe('fetchPrHeadTrackingRef', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('fetches into the remote-tracking ref with real git for local repos', async () => {
|
||||
await fetchPrHeadTrackingRef({ path: '/repo', connectionId: null }, 'origin', 'feature/x')
|
||||
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledWith(
|
||||
['fetch', 'origin', '+refs/heads/feature/x:refs/remotes/origin/feature/x'],
|
||||
{ cwd: '/repo', timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS }
|
||||
)
|
||||
})
|
||||
|
||||
it('throws for an SSH repo, which this process does not serve', async () => {
|
||||
await expect(
|
||||
fetchPrHeadTrackingRef({ path: '/repo', connectionId: 'conn-1' }, 'origin', 'feature/x')
|
||||
).rejects.toThrow('SSH Git provider is not available')
|
||||
expect(gitExecFileAsyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('throws for an SSH repo named only by executionHostId', async () => {
|
||||
await expect(
|
||||
fetchPrHeadTrackingRef({ path: '/repo', executionHostId: 'ssh:gpu' }, 'origin', 'feature/x')
|
||||
@@ -47,21 +25,6 @@ describe('fetchPrHeadTrackingRef', () => {
|
||||
expect(gitExecFileAsyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fetches a GitHub pull head into its remote-scoped Orca ref for local repos', async () => {
|
||||
const localRef = await fetchGitHubPullRequestHeadRef(
|
||||
{ path: '/repo', connectionId: null },
|
||||
'origin',
|
||||
42
|
||||
)
|
||||
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledWith(
|
||||
['fetch', '--no-tags', 'origin', `+refs/pull/42/head:refs/orca/pull/${ORIGIN_COMPONENT}/42`],
|
||||
{ cwd: '/repo', timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS }
|
||||
)
|
||||
expect(localRef).toBe(githubPullRequestHeadLocalRef(ORIGIN_COMPONENT, 42))
|
||||
expect(localRef).toBe(`refs/orca/pull/${ORIGIN_COMPONENT}/42`)
|
||||
})
|
||||
|
||||
it('fails the pull-head fetch when the remote is not configured', async () => {
|
||||
gitExecFileAsyncMock.mockImplementation(async (args: string[]) => {
|
||||
if (args[0] === 'remote' && args[1] === 'get-url') {
|
||||
@@ -79,21 +42,6 @@ describe('fetchPrHeadTrackingRef', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps WSL routing while bounding the pull-head fetch', async () => {
|
||||
await fetchGitHubPullRequestHeadRef({ path: '/repo', connectionId: null }, 'origin', 42, {
|
||||
localGitExecOptions: { cwd: '/repo', wslDistro: 'Ubuntu' }
|
||||
})
|
||||
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], {
|
||||
cwd: '/repo',
|
||||
wslDistro: 'Ubuntu'
|
||||
})
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledWith(
|
||||
['fetch', '--no-tags', 'origin', `+refs/pull/42/head:refs/orca/pull/${ORIGIN_COMPONENT}/42`],
|
||||
{ cwd: '/repo', wslDistro: 'Ubuntu', timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS }
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects a GitHub pull-head fetch for an SSH repo', async () => {
|
||||
await expect(
|
||||
fetchGitHubPullRequestHeadRef({ path: '/repo', connectionId: 'conn-1' }, 'origin', 42)
|
||||
|
||||
@@ -51,14 +51,6 @@ beforeEach(() => {
|
||||
})
|
||||
|
||||
describe('project view layout selection', () => {
|
||||
it('fetches roadmap items with the selected host and filter', async () => {
|
||||
vi.mocked(fetchProjectViewsPage).mockResolvedValue(page([view('roadmap', 'ROADMAP_LAYOUT')]))
|
||||
const result = await getProjectViewTable({ ...args, viewId: 'roadmap' })
|
||||
expect(result).toMatchObject({ ok: true, data: { selectedView: { layout: 'ROADMAP_LAYOUT' } } })
|
||||
expect(fetchAllItems).toHaveBeenCalledWith({ ...args, query: 'status:open' })
|
||||
expect(fetchItemsCountOnly).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('defaults to a roadmap when no table exists across all view pages', async () => {
|
||||
vi.mocked(fetchProjectViewsPage)
|
||||
.mockResolvedValueOnce(page([view('roadmap', 'ROADMAP_LAYOUT')], true))
|
||||
@@ -89,22 +81,6 @@ describe('project view layout selection', () => {
|
||||
expect(fetchAllItems).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fetches board items like a table', async () => {
|
||||
vi.mocked(fetchProjectViewsPage).mockResolvedValue(page([view('board', 'BOARD_LAYOUT')]))
|
||||
const result = await getProjectViewTable({ ...args, viewId: 'board' })
|
||||
expect(result).toMatchObject({ ok: true, data: { selectedView: { layout: 'BOARD_LAYOUT' } } })
|
||||
expect(fetchAllItems).toHaveBeenCalledWith({ ...args, query: 'status:open' })
|
||||
expect(fetchItemsCountOnly).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('defaults to a board when neither a table nor a roadmap exists', async () => {
|
||||
vi.mocked(fetchProjectViewsPage).mockResolvedValue(page([view('board', 'BOARD_LAYOUT')]))
|
||||
expect(await getProjectViewTable(args)).toMatchObject({
|
||||
ok: true,
|
||||
data: { selectedView: { id: 'board' } }
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects an unknown future layout without fetching items', async () => {
|
||||
vi.mocked(fetchProjectViewsPage).mockResolvedValue(page([view('unsupported', 'FUTURE_LAYOUT')]))
|
||||
expect(
|
||||
|
||||
@@ -19,49 +19,6 @@ function loopWithClock(startAt = 0) {
|
||||
}
|
||||
|
||||
describe('createHangWatchdogDetectionLoop', () => {
|
||||
it('does not fire while heartbeats keep arriving', () => {
|
||||
const { loop, onHangDetected, advance } = loopWithClock()
|
||||
for (let i = 0; i < 100; i++) {
|
||||
advance(CHECK_INTERVAL_MS)
|
||||
loop.recordHeartbeat()
|
||||
loop.tick()
|
||||
}
|
||||
expect(onHangDetected).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fires once when heartbeats stop for longer than the timeout', () => {
|
||||
const { loop, onHangDetected, advance } = loopWithClock()
|
||||
loop.recordHeartbeat()
|
||||
for (let i = 0; i < 12; i++) {
|
||||
advance(CHECK_INTERVAL_MS)
|
||||
loop.tick()
|
||||
}
|
||||
expect(onHangDetected).toHaveBeenCalledTimes(1)
|
||||
advance(CHECK_INTERVAL_MS)
|
||||
loop.tick()
|
||||
expect(onHangDetected).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('reports the measured stall duration, not the timeout', () => {
|
||||
const { loop, onHangDetected, advance } = loopWithClock()
|
||||
loop.recordHeartbeat()
|
||||
for (let i = 0; i < 12; i++) {
|
||||
advance(CHECK_INTERVAL_MS)
|
||||
loop.tick()
|
||||
}
|
||||
expect(onHangDetected).toHaveBeenCalledWith(50_000)
|
||||
})
|
||||
|
||||
it('does not fire at exactly the timeout boundary', () => {
|
||||
const { loop, onHangDetected, advance } = loopWithClock()
|
||||
loop.recordHeartbeat()
|
||||
for (let i = 0; i < 9; i++) {
|
||||
advance(CHECK_INTERVAL_MS)
|
||||
loop.tick()
|
||||
}
|
||||
expect(onHangDetected).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('treats a large tick gap as system sleep and restarts the wait', () => {
|
||||
const { loop, onHangDetected, advance } = loopWithClock()
|
||||
loop.recordHeartbeat()
|
||||
@@ -82,30 +39,6 @@ describe('createHangWatchdogDetectionLoop', () => {
|
||||
expect(onHangDetected).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('reports resolution when heartbeats resume after a detected hang', () => {
|
||||
const { loop, onHangDetected, onHangResolved, advance } = loopWithClock()
|
||||
loop.recordHeartbeat()
|
||||
for (let i = 0; i < 12; i++) {
|
||||
advance(CHECK_INTERVAL_MS)
|
||||
loop.tick()
|
||||
}
|
||||
expect(onHangDetected).toHaveBeenCalledTimes(1)
|
||||
advance(CHECK_INTERVAL_MS)
|
||||
loop.recordHeartbeat()
|
||||
expect(onHangResolved).toHaveBeenCalledTimes(1)
|
||||
expect(onHangResolved).toHaveBeenCalledWith(13 * CHECK_INTERVAL_MS)
|
||||
})
|
||||
|
||||
it('does not report resolution when no hang was ever detected', () => {
|
||||
const { loop, onHangResolved, advance } = loopWithClock()
|
||||
for (let i = 0; i < 5; i++) {
|
||||
advance(CHECK_INTERVAL_MS)
|
||||
loop.recordHeartbeat()
|
||||
loop.tick()
|
||||
}
|
||||
expect(onHangResolved).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('can detect a second hang after the first one resolved', () => {
|
||||
const { loop, onHangDetected, onHangResolved, advance } = loopWithClock()
|
||||
loop.recordHeartbeat()
|
||||
|
||||
@@ -35,13 +35,6 @@ describe('fetchWithElectronManualRedirects', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('falls back to the followed URL when the redirect has no Location', async () => {
|
||||
const pending = fetchWithElectronManualRedirects('https://github.com/o.png', {})
|
||||
native.emit('redirect', 301, 'GET', 'https://avatars.example/u/2', {})
|
||||
|
||||
expect((await pending).headers.get('location')).toBe('https://avatars.example/u/2')
|
||||
})
|
||||
|
||||
it('streams the final response body', async () => {
|
||||
const pending = fetchWithElectronManualRedirects('https://github.com/o.png', {})
|
||||
native.emit(
|
||||
|
||||
@@ -2,7 +2,8 @@ import { 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 { _resetSecretStoreForTests, setSecretStore } from '../../shared/secret-store'
|
||||
import { setSecretStore } from '../../shared/secret-store'
|
||||
|
||||
import { reportSecretProtectionGap } from './secret-protection-report'
|
||||
|
||||
const WEAK = 'Secrets are obfuscated with a built-in key.'
|
||||
@@ -66,12 +67,6 @@ describe('reportSecretProtectionGap', () => {
|
||||
expect(logged).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('stays silent from a clean start when secrets are properly sealed', () => {
|
||||
installStore(null)
|
||||
expect(report()).toBeNull()
|
||||
expect(logged).toEqual([])
|
||||
})
|
||||
|
||||
it('re-reports on demand for support, without disturbing stored state', () => {
|
||||
installStore(WEAK)
|
||||
report()
|
||||
@@ -87,10 +82,4 @@ describe('reportSecretProtectionGap', () => {
|
||||
expect(report()).toBe(WEAK)
|
||||
expect(logged).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('does not throw startup when no store is installed', () => {
|
||||
_resetSecretStoreForTests()
|
||||
expect(() => report()).not.toThrow()
|
||||
expect(logged[0]).toContain('could not determine at-rest protection')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -99,16 +99,6 @@ async function provision(): Promise<unknown> {
|
||||
})
|
||||
}
|
||||
|
||||
it("records the managed server that serves a recipe VM's SSH host", async () => {
|
||||
setupManagedSshRecipe()
|
||||
expect(await provision()).toMatchObject({
|
||||
ok: true,
|
||||
connectionType: 'ssh',
|
||||
environmentId: 'env-managed-vm',
|
||||
runtime: { connectionMode: 'ssh', runtimeEnvironmentId: 'env-managed-vm' }
|
||||
})
|
||||
})
|
||||
|
||||
it("reconnects a resumed VM's SSH host instead of asking for a pairing code", async () => {
|
||||
const { userDataPath, store } = setupManagedSshRecipe()
|
||||
const provisioned = await provision()
|
||||
|
||||
@@ -36,21 +36,6 @@ describe('publishing a verified managed host status', () => {
|
||||
clearSshHostServerStatus('ssh-2')
|
||||
})
|
||||
|
||||
it('replaces the deferred diagnostic in the host store and both subscribers', () => {
|
||||
setSshHostServerStatus('ssh-1', deferred)
|
||||
mocks.getState.mockReturnValue(connection('connected'))
|
||||
publishHostServerStatus('ssh-1', ready)
|
||||
expect(getSshHostServerStatus('ssh-1')).toEqual(ready)
|
||||
expect(mocks.notify).toHaveBeenCalledWith(
|
||||
'ssh-1',
|
||||
expect.objectContaining({ managedServer: ready })
|
||||
)
|
||||
expect(mocks.send).toHaveBeenCalledWith(
|
||||
'ssh:state-changed',
|
||||
expect.objectContaining({ state: expect.objectContaining({ managedServer: ready }) })
|
||||
)
|
||||
})
|
||||
|
||||
it('preserves disconnected contact instead of inventing a connection', () => {
|
||||
mocks.getState.mockReturnValue(connection('disconnected'))
|
||||
publishHostServerStatus('ssh-1', ready)
|
||||
@@ -60,41 +45,6 @@ describe('publishing a verified managed host status', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('retains the current unverifiable host evidence when publishing it', () => {
|
||||
mocks.getState.mockReturnValue(connection('connected'))
|
||||
const unverifiable = {
|
||||
...ready,
|
||||
serving: { state: 'unverifiable', detail: 'The process is live but not answering.' }
|
||||
} as const
|
||||
publishHostServerStatus('ssh-1', unverifiable)
|
||||
expect(getSshHostServerStatus('ssh-1')).toEqual(unverifiable)
|
||||
expect(mocks.notify.mock.calls[0]?.[1].managedServer).toEqual(unverifiable)
|
||||
})
|
||||
|
||||
it('records a host without a connection and leaves another host untouched', () => {
|
||||
mocks.getState.mockReturnValue(undefined)
|
||||
setSshHostServerStatus('ssh-2', deferred)
|
||||
publishHostServerStatus('ssh-1', ready)
|
||||
expect(getSshHostServerStatus('ssh-1')).toEqual(ready)
|
||||
expect(getSshHostServerStatus('ssh-2')).toEqual(deferred)
|
||||
expect(mocks.notify).not.toHaveBeenCalled()
|
||||
expect(mocks.send).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("clears a verified host's deferral and unverifiable notes", () => {
|
||||
mocks.getState.mockReturnValue(connection('connected'))
|
||||
setSshHostServerStatus('ssh-1', {
|
||||
...deferred,
|
||||
serving: { state: 'unverifiable', detail: 'No reply.' }
|
||||
})
|
||||
clearManagedServerNotes('ssh-1', 'env-1')
|
||||
expect(getSshHostServerStatus('ssh-1')).toEqual(ready)
|
||||
expect(mocks.notify).toHaveBeenCalledWith(
|
||||
'ssh-1',
|
||||
expect.objectContaining({ managedServer: ready })
|
||||
)
|
||||
})
|
||||
|
||||
it('leaves a relay route, another server, or an unknown host as it was', () => {
|
||||
mocks.getState.mockReturnValue(connection('connected'))
|
||||
const relay = { kind: 'relay', reason: 'source_changed' } as const
|
||||
|
||||
@@ -80,18 +80,6 @@ afterEach(() => {
|
||||
|
||||
// Spawn env prep runs before #35813's hold: only a launch someone asked for may start the distro (E9).
|
||||
describe('WSL spawn host env', () => {
|
||||
it('runs a launch someone asked for as a user act on its distro', async () => {
|
||||
const seen: boolean[] = []
|
||||
await resolve(false, seen)
|
||||
expect(seen).toEqual([true])
|
||||
})
|
||||
|
||||
it('runs a passive restore outside any user act, so its prep is gated', async () => {
|
||||
const seen: boolean[] = []
|
||||
await resolve(true, seen)
|
||||
expect(seen).toEqual([false])
|
||||
})
|
||||
|
||||
it('never turns a passive restore with no named distro into a user act on the default one', async () => {
|
||||
const seen: boolean[] = []
|
||||
await resolve(true, seen, {
|
||||
@@ -101,12 +89,6 @@ describe('WSL spawn host env', () => {
|
||||
expect(seen).toEqual([false])
|
||||
})
|
||||
|
||||
it('never turns a host-target spawn into a user act on the default distro', async () => {
|
||||
const seen: boolean[] = []
|
||||
await resolve(false, seen, { target: { runtime: 'host' }, expectedWslDistro: null })
|
||||
expect(seen).toEqual([false])
|
||||
})
|
||||
|
||||
it('a WSL launch someone asked for, with no named distro, acts on the default one', async () => {
|
||||
const seen: boolean[] = []
|
||||
await resolve(false, seen, {
|
||||
@@ -122,9 +104,4 @@ describe('WSL spawn host env', () => {
|
||||
expect(mocks.blockedPath).toHaveBeenCalledWith(HOME)
|
||||
expect(mocks.ensureBackfill).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('still starts the state-DB recovery when the distro runs', async () => {
|
||||
await resolve(true, [])
|
||||
expect(mocks.ensureBackfill).toHaveBeenCalledWith(HOME)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -98,19 +98,6 @@ describe('the quit checkpoint in a layout-owner build', () => {
|
||||
rmSync(testState.dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('records main’s own quit capture before staging, though the window’s save lacks it', () => {
|
||||
store.setWorkspaceSession(session(), 'local')
|
||||
const captured = record(PANE_A, 2)
|
||||
quitRecords.push(captured)
|
||||
|
||||
expect(stage(session())).toEqual({ ok: true })
|
||||
|
||||
expect(quitResumeRecordsFor).toHaveBeenCalledOnce()
|
||||
expect(store.getWorkspaceSession('local').sleepingAgentSessionsByPaneKey?.[PANE_A]).toEqual(
|
||||
captured
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps a wake main recorded that the window had not seen yet', () => {
|
||||
// Main woke tab-b (a phone showed it) after the window last saw its record.
|
||||
store.setWorkspaceSession(session(), 'local')
|
||||
|
||||
@@ -2,12 +2,9 @@ import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:f
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { resolveCliCommand } from '../../shared/node-cli-command-resolution'
|
||||
|
||||
import {
|
||||
_resetWindowsCopyVerdictsForTests,
|
||||
guestNativeSpawnEnv,
|
||||
isWslHostOrcadProcess,
|
||||
ORCAD_WSL_HOST_ENV,
|
||||
resolveGuestNativeProgram
|
||||
} from './wsl-guest-windows-drive-path'
|
||||
|
||||
@@ -49,29 +46,10 @@ describe.skipIf(process.platform === 'win32')('resolveGuestNativeProgram', () =>
|
||||
install(join(drive, 'npm'))
|
||||
expect(resolveGuestNativeProgram('claude', options(), undefined, [drive])).toBeNull()
|
||||
})
|
||||
|
||||
it('leaves a program missing everywhere as its bare name, so the spawn fails as not installed', () => {
|
||||
expect(resolveGuestNativeProgram('claude', options(), undefined, [drive])).toBe('claude')
|
||||
})
|
||||
|
||||
it('resolves exactly as before off a WSL host (native Linux, macOS, SSH hosts, the desktop)', () => {
|
||||
const windowsCopy = install(join(drive, 'npm'))
|
||||
expect(resolveGuestNativeProgram('claude', options(), undefined, [])).toBe(windowsCopy)
|
||||
})
|
||||
})
|
||||
|
||||
describe.skipIf(process.platform === 'win32')('the Windows-copy check', () => {
|
||||
const options = () => ({ pathEnv: `${native}:${drive}/npm`, homePath: join(root, 'home') })
|
||||
const counting = () => vi.fn(resolveCliCommand)
|
||||
|
||||
it('scans the drive-mounted PATH once for repeated lookups of the same PATH', () => {
|
||||
install(join(drive, 'npm'))
|
||||
const resolve = counting()
|
||||
expect(resolveGuestNativeProgram('claude', options(), resolve, [drive])).toBeNull()
|
||||
expect(resolveGuestNativeProgram('claude', options(), resolve, [drive])).toBeNull()
|
||||
// One native lookup per call, one Windows-copy scan in total.
|
||||
expect(resolve).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('still finds a WSL install made after the verdict was cached', () => {
|
||||
install(join(drive, 'npm'))
|
||||
@@ -88,42 +66,4 @@ describe.skipIf(process.platform === 'win32')('the Windows-copy check', () => {
|
||||
vi.advanceTimersByTime(30_000)
|
||||
expect(resolveGuestNativeProgram('claude', options(), undefined, [drive])).toBeNull()
|
||||
})
|
||||
|
||||
it('caches nothing off a WSL host (native Linux, macOS, SSH hosts, the desktop)', () => {
|
||||
const resolve = counting()
|
||||
expect(resolveGuestNativeProgram('claude', options(), resolve, [])).toBe('claude')
|
||||
const windowsCopy = install(join(drive, 'npm'))
|
||||
expect(resolveGuestNativeProgram('claude', options(), resolve, [])).toBe(windowsCopy)
|
||||
expect(resolve).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('guestNativeSpawnEnv', () => {
|
||||
it('drops Windows drive entries from a WSL-host agent child PATH', () => {
|
||||
expect(guestNativeSpawnEnv({ PATH: '/usr/bin:/mnt/c/npm', HOME: '/h' }, ['/mnt/c'])).toEqual({
|
||||
PATH: '/usr/bin',
|
||||
HOME: '/h'
|
||||
})
|
||||
})
|
||||
|
||||
it('returns the env untouched where there are no drive mounts', () => {
|
||||
const env = { PATH: '/usr/bin:/mnt/c/npm' }
|
||||
expect(guestNativeSpawnEnv(env, [])).toBe(env)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the WSL-host gate', () => {
|
||||
const marked = { [ORCAD_WSL_HOST_ENV]: '1', WSL_DISTRO_NAME: 'Ubuntu' }
|
||||
|
||||
it('stays off on macOS, the Windows desktop, native Linux and SSH-host orcad', () => {
|
||||
expect(isWslHostOrcadProcess(marked, 'darwin', () => true)).toBe(false)
|
||||
expect(isWslHostOrcadProcess(marked, 'win32', () => true)).toBe(false)
|
||||
expect(isWslHostOrcadProcess({}, 'linux', () => false)).toBe(false)
|
||||
// An SSH host's orcad is launched with nohup and never gets the WSL-host marker.
|
||||
expect(isWslHostOrcadProcess({ ORCA_USER_DATA: '/srv/orca' }, 'linux', () => false)).toBe(false)
|
||||
})
|
||||
|
||||
it('turns on only for orcad launched as a WSL host inside the guest', () => {
|
||||
expect(isWslHostOrcadProcess(marked, 'linux', () => false)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -52,59 +52,4 @@ describe('redactLinuxPackageInstallText', () => {
|
||||
'ci: incident in circuit'
|
||||
)
|
||||
})
|
||||
|
||||
it('survives an unavailable user record', () => {
|
||||
vi.spyOn(os, 'userInfo').mockImplementation(() => {
|
||||
throw new Error('no passwd entry')
|
||||
})
|
||||
expect(diagnostic.redactLinuxPackageInstallText('dpkg: unrecoverable error', null)).toBe(
|
||||
'dpkg: unrecoverable error'
|
||||
)
|
||||
})
|
||||
|
||||
it('bounds the result at 1024 characters', () => {
|
||||
expect(diagnostic.redactLinuxPackageInstallText('a'.repeat(2_000), null)).toHaveLength(1_024)
|
||||
expect(diagnostic.redactLinuxPackageInstallText('a'.repeat(1_024), null)).toHaveLength(1_024)
|
||||
})
|
||||
|
||||
it('returns null when no visible text remains', () => {
|
||||
expect(diagnostic.redactLinuxPackageInstallText('', null)).toBeNull()
|
||||
expect(diagnostic.redactLinuxPackageInstallText(' \n\t ', null)).toBeNull()
|
||||
expect(diagnostic.redactLinuxPackageInstallText(`${ESC}[0m`, null)).toBeNull()
|
||||
expect(diagnostic.redactLinuxPackageInstallText(null, null)).toBeNull()
|
||||
expect(diagnostic.redactLinuxPackageInstallText(undefined, null)).toBeNull()
|
||||
})
|
||||
|
||||
it('normalizes errors, objects, and primitives', () => {
|
||||
expect(diagnostic.redactLinuxPackageInstallText(new Error('pkexec failed'), null)).toBe(
|
||||
'pkexec failed'
|
||||
)
|
||||
expect(diagnostic.redactLinuxPackageInstallText({ code: 127 }, null)).toBe('{"code":127}')
|
||||
expect(diagnostic.redactLinuxPackageInstallText(127, null)).toBe('127')
|
||||
})
|
||||
|
||||
it('returns null for an unserializable object', () => {
|
||||
const circular: Record<string, unknown> = {}
|
||||
circular.self = circular
|
||||
expect(diagnostic.redactLinuxPackageInstallText(circular, null)).toBeNull()
|
||||
})
|
||||
|
||||
it('ignores an empty package path', () => {
|
||||
expect(diagnostic.redactLinuxPackageInstallText('plain output', '')).toBe('plain output')
|
||||
})
|
||||
})
|
||||
|
||||
describe('createUpdaterDiagnosticLogger', () => {
|
||||
it('forwards every updater level to the matching console method', () => {
|
||||
const logger = diagnostic.createUpdaterDiagnosticLogger()
|
||||
logger.info('a')
|
||||
logger.warn('b')
|
||||
logger.error('c')
|
||||
logger.debug('d')
|
||||
|
||||
expect(console.info).toHaveBeenCalledWith('[autoUpdater]', 'a')
|
||||
expect(console.warn).toHaveBeenCalledWith('[autoUpdater]', 'b')
|
||||
expect(console.error).toHaveBeenCalledWith('[autoUpdater]', 'c')
|
||||
expect(console.debug).toHaveBeenCalledWith('[autoUpdater]', 'd')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -65,18 +65,6 @@ afterEach(async () => {
|
||||
})
|
||||
|
||||
describe('loadLocalBuildCandidate', () => {
|
||||
it('returns a sanitized, architecture-specific feed after hash validation', async () => {
|
||||
const { manifestPath } = await fixture()
|
||||
const candidate = await loadLocalBuildCandidate(manifestPath, 'arm64', {
|
||||
readCompatibility: async () => compatibility()
|
||||
})
|
||||
|
||||
expect(candidate.version).toBe('1.2.3-local.1')
|
||||
expect([...candidate.artifacts.keys()]).toEqual(['orca-macos-arm64.zip'])
|
||||
expect(candidate.manifestContent).toContain('orca-macos-arm64.zip')
|
||||
await candidate.close()
|
||||
})
|
||||
|
||||
it('rejects mismatched hashes and traversal paths', async () => {
|
||||
const badHash = await fixture({ sha512: Buffer.alloc(64).toString('base64') })
|
||||
await expect(
|
||||
@@ -160,13 +148,4 @@ describe('loadLocalBuildCandidate', () => {
|
||||
await candidate.close()
|
||||
}
|
||||
)
|
||||
|
||||
it('requires exactly one ZIP for the running architecture', async () => {
|
||||
const { manifestPath } = await fixture()
|
||||
await expect(
|
||||
loadLocalBuildCandidate(manifestPath, 'x64', {
|
||||
readCompatibility: async () => compatibility()
|
||||
})
|
||||
).rejects.toThrow('exactly one x64 Orca ZIP')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,168 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { evaluateOrcadActivation } from './orcad-activation-gate'
|
||||
import { classifyOrcadHostUnavailable } from '../../orcad/orcad-host-unavailable'
|
||||
import type { ServeReadiness } from '../../server/serve-readiness'
|
||||
import type { OrcadHealth, TerminalDaemonHealth } from '../../orcad/orcad-health'
|
||||
|
||||
const EXPECTED = { buildHash: 'abc123def4567890', fullVersion: '0.2.0+bb01' }
|
||||
|
||||
function daemon(overrides: Partial<TerminalDaemonHealth> = {}): TerminalDaemonHealth {
|
||||
return {
|
||||
state: 'live',
|
||||
ownsFreshSessions: true,
|
||||
pid: 4242,
|
||||
buildVersion: '0.2.0+bb01',
|
||||
entryPath: '/home/u/.orca-remote/orcad-0.2.0+bb01/daemon-entry.js',
|
||||
protocolVersion: 3,
|
||||
cgroupUnit: null,
|
||||
selfTest: { ok: true, coverage: 'pty-spawn', verdict: 'healthy', durationMs: 12 },
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function health(overrides: Partial<OrcadHealth> = {}): OrcadHealth {
|
||||
return {
|
||||
buildHash: EXPECTED.buildHash,
|
||||
buildVersion: EXPECTED.fullVersion,
|
||||
nodeVersion: '20.11.0',
|
||||
nodeAbi: '115',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
pid: 4200,
|
||||
terminalDaemon: daemon(),
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function readiness(overrides: Partial<ServeReadiness> = {}): ServeReadiness {
|
||||
return {
|
||||
runtimeId: 'runtime-1',
|
||||
boundEndpoint: 'ws://127.0.0.1:7777',
|
||||
advertisedEndpoint: null,
|
||||
managedWslCliReconciliation: 'settled',
|
||||
pairing: { available: false, reason: 'disabled_by_operator', guidance: 'n/a' },
|
||||
health: health(),
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('evaluateOrcadActivation', () => {
|
||||
it('activates a candidate that proved a real PTY round trip', () => {
|
||||
const verdict = evaluateOrcadActivation(readiness(), EXPECTED)
|
||||
expect(verdict).toEqual({ decision: 'activate', coverage: 'pty-spawn', warnings: [] })
|
||||
})
|
||||
|
||||
it('refuses when the candidate never published readiness', () => {
|
||||
const verdict = evaluateOrcadActivation(null, EXPECTED)
|
||||
expect(verdict).toMatchObject({ decision: 'reject', code: 'orcad_activation_no_readiness' })
|
||||
})
|
||||
|
||||
it('refuses a readiness payload with no health, rather than reading silence as healthy', () => {
|
||||
const { health: _dropped, ...withoutHealth } = readiness()
|
||||
const verdict = evaluateOrcadActivation(withoutHealth as ServeReadiness, EXPECTED)
|
||||
expect(verdict).toMatchObject({ decision: 'reject', code: 'orcad_activation_no_health' })
|
||||
})
|
||||
|
||||
it('refuses when a different build answered — a stale process holding the port', () => {
|
||||
const verdict = evaluateOrcadActivation(
|
||||
readiness({ health: health({ buildHash: '0000000000000000' }) }),
|
||||
EXPECTED
|
||||
)
|
||||
expect(verdict).toMatchObject({ decision: 'reject', code: 'orcad_activation_build_mismatch' })
|
||||
})
|
||||
|
||||
it('refuses a listening orcad whose terminal daemon is absent', () => {
|
||||
const verdict = evaluateOrcadActivation(
|
||||
readiness({
|
||||
health: health({
|
||||
terminalDaemon: daemon({
|
||||
state: 'absent',
|
||||
ownsFreshSessions: false,
|
||||
selfTest: { ok: false, coverage: 'pty-spawn', verdict: 'no-daemon', durationMs: 1 }
|
||||
})
|
||||
})
|
||||
}),
|
||||
EXPECTED
|
||||
)
|
||||
expect(verdict).toMatchObject({ decision: 'reject', code: 'orcad_activation_daemon_absent' })
|
||||
// Cold daemon startup is transient; later connects must remain eligible to deploy.
|
||||
expect(classifyOrcadHostUnavailable({ code: 'orcad_activation_daemon_absent' })).toBeNull()
|
||||
})
|
||||
|
||||
it('refuses a degraded daemon, whose fresh terminals would not survive a restart', () => {
|
||||
const verdict = evaluateOrcadActivation(
|
||||
readiness({
|
||||
health: health({ terminalDaemon: daemon({ state: 'degraded', ownsFreshSessions: false }) })
|
||||
}),
|
||||
EXPECTED
|
||||
)
|
||||
expect(verdict).toMatchObject({ decision: 'reject', code: 'orcad_activation_daemon_degraded' })
|
||||
})
|
||||
|
||||
it('refuses a live daemon that failed its PTY spawn probe', () => {
|
||||
const verdict = evaluateOrcadActivation(
|
||||
readiness({
|
||||
health: health({
|
||||
terminalDaemon: daemon({
|
||||
selfTest: {
|
||||
ok: false,
|
||||
coverage: 'pty-spawn',
|
||||
verdict: 'pty-spawn-unhealthy',
|
||||
durationMs: 30
|
||||
}
|
||||
})
|
||||
})
|
||||
}),
|
||||
EXPECTED
|
||||
)
|
||||
expect(verdict).toMatchObject({
|
||||
decision: 'reject',
|
||||
code: 'orcad_activation_pty_self_test_failed'
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses a green daemon that does not own fresh sessions', () => {
|
||||
const verdict = evaluateOrcadActivation(
|
||||
readiness({ health: health({ terminalDaemon: daemon({ ownsFreshSessions: false }) }) }),
|
||||
EXPECTED
|
||||
)
|
||||
expect(verdict).toMatchObject({
|
||||
decision: 'reject',
|
||||
code: 'orcad_activation_no_persistent_terminals'
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses a candidate that is not listening', () => {
|
||||
const verdict = evaluateOrcadActivation(readiness({ boundEndpoint: null }), EXPECTED)
|
||||
expect(verdict).toMatchObject({ decision: 'reject', code: 'orcad_activation_not_listening' })
|
||||
})
|
||||
|
||||
it('activates handshake-only coverage but never records it as a proven PTY', () => {
|
||||
const verdict = evaluateOrcadActivation(
|
||||
readiness({
|
||||
health: health({
|
||||
platform: 'win32',
|
||||
terminalDaemon: daemon({
|
||||
selfTest: { ok: true, coverage: 'handshake', verdict: 'healthy', durationMs: 5 }
|
||||
})
|
||||
})
|
||||
}),
|
||||
EXPECTED
|
||||
)
|
||||
expect(verdict).toMatchObject({ decision: 'activate', coverage: 'handshake' })
|
||||
expect(verdict.decision === 'activate' && verdict.warnings[0]).toContain(
|
||||
'covered the daemon handshake only'
|
||||
)
|
||||
})
|
||||
|
||||
it('checks identity before health, so a wrong-build green payload cannot pass', () => {
|
||||
const verdict = evaluateOrcadActivation(
|
||||
readiness({
|
||||
health: health({ buildHash: 'ffffffffffffffff', terminalDaemon: daemon() })
|
||||
}),
|
||||
EXPECTED
|
||||
)
|
||||
expect(verdict).toMatchObject({ code: 'orcad_activation_build_mismatch' })
|
||||
})
|
||||
})
|
||||
@@ -142,10 +142,4 @@ describe.skipIf(process.platform === 'win32')('snapshot room on a real shell (#3
|
||||
expect(output.trim()).toBe('SNAPSHOT_SPACE UNMEASURED')
|
||||
expect(parseOrcadSnapshotSpace(output)).toBeNull()
|
||||
})
|
||||
|
||||
it('reads no room answer from a host that printed none', () => {
|
||||
expect(parseOrcadSnapshotSpace('')).toBeNull()
|
||||
expect(orcadSnapshotShortfallKb(null)).toBeNull()
|
||||
expect(orcadSnapshotShortfallKb({ neededKb: 0, availableKb: 0, reclaimKb: 0 })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -50,38 +50,6 @@ describe('provider timeline turns', () => {
|
||||
expect(row?.revision).toBeGreaterThan(runningRow?.revision ?? Infinity)
|
||||
})
|
||||
|
||||
it('records a cancelled turn as interrupted with the cancellation verdict', async () => {
|
||||
const rig = await openProviderTimelineRig()
|
||||
rig.assembler.apply({ type: 'turn.open', turn: 'turn-1', at: 1_000 })
|
||||
rig.assembler.apply({
|
||||
type: 'turn.end',
|
||||
at: 2_000,
|
||||
state: 'interrupted',
|
||||
outcome: 'cancellation'
|
||||
})
|
||||
expect(await rig.turn('turn-1')).toMatchObject({
|
||||
state: 'interrupted',
|
||||
outcome: 'cancellation',
|
||||
completedAt: 2_000
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps a provider-reported failure a completed turn whose verdict says it failed', async () => {
|
||||
const rig = await openProviderTimelineRig()
|
||||
rig.assembler.apply({ type: 'turn.open', turn: 'turn-1', at: 1_000 })
|
||||
rig.assembler.apply({ type: 'turn.end', at: 2_000, state: 'completed', outcome: 'failure' })
|
||||
expect(await rig.turn('turn-1')).toMatchObject({ state: 'completed', outcome: 'failure' })
|
||||
})
|
||||
|
||||
it('leaves the verdict absent when the provider gave none', async () => {
|
||||
const rig = await openProviderTimelineRig()
|
||||
rig.assembler.apply({ type: 'turn.open', turn: 'turn-1', at: 1_000 })
|
||||
rig.assembler.apply({ type: 'turn.end', at: 2_000, state: 'completed' })
|
||||
const turn = await rig.turn('turn-1')
|
||||
expect(turn?.state).toBe('completed')
|
||||
expect(turn).not.toHaveProperty('outcome')
|
||||
})
|
||||
|
||||
it('mints a turn id when the provider names none, and keys a turn no send opened by its own row', async () => {
|
||||
const rig = await openProviderTimelineRig()
|
||||
rig.assembler.apply({ type: 'turn.open', at: 1_000 })
|
||||
|
||||
-10
@@ -186,14 +186,4 @@ describe('identity bounding at admission', () => {
|
||||
)
|
||||
expect(removal.page.removedItemIds).toEqual([appended.itemId])
|
||||
})
|
||||
|
||||
it('keeps bounded keys deterministic and a fixed point of re-derivation', () => {
|
||||
const oversized = 'x'.repeat(2 * 1024 * 1024)
|
||||
const bounded = boundJournalKeyComponent(oversized)
|
||||
expect(bounded).toBe(boundJournalKeyComponent(oversized))
|
||||
expect(boundJournalKeyComponent(bounded)).toBe(bounded)
|
||||
expect(bounded.length).toBeLessThan(2048)
|
||||
expect(boundJournalKeyComponent(`${oversized}y`)).not.toBe(bounded)
|
||||
expect(boundJournalKeyComponent('short')).toBe('short')
|
||||
})
|
||||
})
|
||||
|
||||
-38
@@ -147,23 +147,6 @@ it('ends the child at once when Claude refuses the interrupt, and says only that
|
||||
expect(texts.some((text) => text.includes("didn't stop"))).toBe(false)
|
||||
})
|
||||
|
||||
it('ends the child when the interrupt fails, with no unconfirmed row', async () => {
|
||||
fixture.claude.routes.interrupt = () => {
|
||||
throw new Error('control request lost')
|
||||
}
|
||||
const connection = fixture.claude.connections[0]!
|
||||
const eventsAtClose = stopEventsAtClose(connection)
|
||||
await openTurn(connection)
|
||||
|
||||
await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } })
|
||||
await laneDrained()
|
||||
|
||||
expect(connection.closed).toBe(true)
|
||||
expect(eventsAtClose()).toBe(1)
|
||||
expect(await turnOutcome()).toBe('cancellation')
|
||||
expect(await statusTexts()).toEqual(['Cancellation requested.'])
|
||||
})
|
||||
|
||||
it('ends the child within the grace when Claude never answers the interrupt', async () => {
|
||||
fixture.claude.routes.interrupt = NEVER_ANSWERS
|
||||
const connection = fixture.claude.connections[0]!
|
||||
@@ -217,27 +200,6 @@ it('ends background work Claude runs when the Stop ends the child', async () =>
|
||||
expect(connection.closed).toBe(true)
|
||||
})
|
||||
|
||||
it('starts a new child for the next send after a Stop, on the same Claude conversation', async () => {
|
||||
const connection = fixture.claude.connections[0]!
|
||||
await openTurn(connection)
|
||||
await stop()
|
||||
frame(connection, INTERRUPTED_RESULT)
|
||||
await laneDrained()
|
||||
|
||||
const next = await send('Carry on.')
|
||||
const resumed = await eventually(() => {
|
||||
const started = fixture.claude.connections.at(-1)
|
||||
expect(started).not.toBe(connection)
|
||||
expect(started && wrote(started, 'Carry on.')).toBe(true)
|
||||
return started!
|
||||
})
|
||||
expect(fixture.store.getRecord(SESSION)?.providerHandleChain.at(-1)?.handle).toMatchObject({
|
||||
nativeId: PROVIDER_SESSION_ID
|
||||
})
|
||||
expect(resumed.closed).toBe(false)
|
||||
expect(await dispatch(next)).toMatchObject({ state: 'pending' })
|
||||
})
|
||||
|
||||
it('delivers a send issued with the pre-Stop fence during the Stop to the resumed child only', async () => {
|
||||
const connection = fixture.claude.connections[0]!
|
||||
await openTurn(connection)
|
||||
|
||||
-29
@@ -17,7 +17,6 @@ import {
|
||||
statusNotes
|
||||
} from './structured-agent-session-restart-interruption-test-harness'
|
||||
import type { StructuredAgentSessionHost } from './structured-agent-session-host'
|
||||
import { previousExitUnverifiableRefusal } from './structured-agent-session-child-close'
|
||||
|
||||
type Restarted = Awaited<ReturnType<typeof interruptedRestart>>
|
||||
|
||||
@@ -145,16 +144,6 @@ it('continues when reading the restart offer hangs', async () => {
|
||||
}
|
||||
}, 10_000)
|
||||
|
||||
it('continues when the restart offer cannot be read', async () => {
|
||||
const { host, dispatch } = await interruptedRestart()
|
||||
const turnItemId = await cutTurn(host)
|
||||
vi.spyOn(host.deps.recoveryCapsule!, 'list').mockRejectedValue(new Error('unreadable'))
|
||||
|
||||
await host.restartResume.continueInterrupted(SESSION, turnItemId)
|
||||
|
||||
await vi.waitFor(() => expect(dispatch).toHaveBeenCalledOnce())
|
||||
})
|
||||
|
||||
it('answers once Orca accepted it, while the agent is still starting', async () => {
|
||||
const { host, acquire, dispatch } = await interruptedRestart()
|
||||
const turnItemId = await cutTurn(host)
|
||||
@@ -217,21 +206,3 @@ it('continues a reply the user had steered before Orca stopped', async () => {
|
||||
await vi.waitFor(() => expect(dispatch).toHaveBeenCalledOnce())
|
||||
expect(sentTexts(dispatch)).toEqual([restartContinuationMessage(marker!)])
|
||||
})
|
||||
|
||||
it('answers a refusal before anything was accepted, and a retry adds no note to the chat', async () => {
|
||||
const { host, dispatch } = await interruptedRestart()
|
||||
const turnItemId = await cutTurn(host)
|
||||
const notesBefore = await statusNotes(host)
|
||||
vi.spyOn(host, 'send').mockResolvedValue({
|
||||
ok: false,
|
||||
refusal: previousExitUnverifiableRefusal()
|
||||
})
|
||||
|
||||
const first = await host.restartResume.continueInterrupted(SESSION, turnItemId)
|
||||
const retry = await host.restartResume.continueInterrupted(SESSION, turnItemId)
|
||||
|
||||
expect([first.outcome, retry.outcome]).toEqual(['refused', 'refused'])
|
||||
// Refusal belongs in the click response, with no journal note.
|
||||
expect(await statusNotes(host)).toEqual(notesBefore)
|
||||
expect(dispatch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { chmod, mkdir, mkdtemp, rm, symlink, writeFile, link } from 'node:fs/promises'
|
||||
import { mkdir, mkdtemp, rm, symlink, writeFile, link } from 'node:fs/promises'
|
||||
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { NATIVE_CHAT_VISUAL_MAX_BYTES } from '../../shared/native-chat/native-chat-visual-directive'
|
||||
import { nativeChatScratchFolderFor } from './native-chat-scratch-folder'
|
||||
import { nativeChatVisualRevision, readNativeChatVisualFile } from './native-chat-visual-file-read'
|
||||
import { readNativeChatVisualFile } from './native-chat-visual-file-read'
|
||||
|
||||
const posixIt = process.platform === 'win32' ? it.skip : it
|
||||
|
||||
@@ -22,30 +23,7 @@ afterEach(async () => {
|
||||
await rm(stateDirectory, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
describe('nativeChatScratchFolderFor', () => {
|
||||
it('places each chat in its own hashed folder under the state directory', () => {
|
||||
const alpha = nativeChatScratchFolderFor('/state', 'session-alpha')
|
||||
const beta = nativeChatScratchFolderFor('/state', 'session-beta')
|
||||
expect(alpha).toMatch(/chat-scratch[\\/][0-9a-f]{32}$/)
|
||||
expect(alpha.startsWith(join('/state', 'chat-scratch'))).toBe(true)
|
||||
expect(alpha).not.toBe(beta)
|
||||
})
|
||||
})
|
||||
|
||||
describe('readNativeChatVisualFile', () => {
|
||||
it('reads a UTF-8 visual with its revision and size', async () => {
|
||||
const html = '<!doctype html><p>Grüße</p>'
|
||||
await writeFile(join(folder, 'chart.html'), html)
|
||||
const result = await readNativeChatVisualFile(folder, 'chart.html')
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
html,
|
||||
revision: nativeChatVisualRevision(Buffer.from(html)),
|
||||
sizeBytes: Buffer.byteLength(html),
|
||||
path: join(folder, 'chart.html')
|
||||
})
|
||||
})
|
||||
|
||||
it('answers unchanged without the bytes when the client already holds the revision', async () => {
|
||||
await writeFile(join(folder, 'chart.html'), '<p>a</p>')
|
||||
const first = await readNativeChatVisualFile(folder, 'chart.html')
|
||||
@@ -65,18 +43,6 @@ describe('readNativeChatVisualFile', () => {
|
||||
expect(changed).toMatchObject({ ok: true, html: '<p>b</p>' })
|
||||
})
|
||||
|
||||
it('reports a missing file or a missing folder as not_found', async () => {
|
||||
expect(await readNativeChatVisualFile(folder, 'nope.html')).toEqual({
|
||||
ok: false,
|
||||
error: 'not_found'
|
||||
})
|
||||
const absent = nativeChatScratchFolderFor(stateDirectory, 'session-never')
|
||||
expect(await readNativeChatVisualFile(absent, 'chart.html')).toEqual({
|
||||
ok: false,
|
||||
error: 'not_found'
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses names that are not a bare visual file name', async () => {
|
||||
await mkdir(join(stateDirectory, 'other'), { recursive: true })
|
||||
await writeFile(join(stateDirectory, 'other', 'secret.html'), 'secret')
|
||||
@@ -134,14 +100,6 @@ describe('readNativeChatVisualFile', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses a directory named like a visual', async () => {
|
||||
await mkdir(join(folder, 'dir.html'))
|
||||
expect(await readNativeChatVisualFile(folder, 'dir.html')).toEqual({
|
||||
ok: false,
|
||||
error: 'not_a_file'
|
||||
})
|
||||
})
|
||||
|
||||
posixIt('refuses a FIFO without waiting for a writer', async () => {
|
||||
execFileSync('mkfifo', [join(folder, 'pipe.html')])
|
||||
expect(await readNativeChatVisualFile(folder, 'pipe.html')).toEqual({
|
||||
@@ -179,32 +137,4 @@ describe('readNativeChatVisualFile', () => {
|
||||
await link(join(folder, 'a.html'), join(folder, 'b.html'))
|
||||
expect(await readNativeChatVisualFile(folder, 'b.html')).toMatchObject({ ok: true })
|
||||
})
|
||||
|
||||
it('reads the replacement after a file is swapped for new content', async () => {
|
||||
await writeFile(join(folder, 'chart.html'), '<p>old</p>')
|
||||
await rm(join(folder, 'chart.html'))
|
||||
await writeFile(join(folder, 'chart.html'), '<p>new</p>')
|
||||
expect(await readNativeChatVisualFile(folder, 'chart.html')).toMatchObject({
|
||||
ok: true,
|
||||
html: '<p>new</p>'
|
||||
})
|
||||
})
|
||||
|
||||
posixIt('reports an unexpected filesystem fault without the host path', async () => {
|
||||
await writeFile(join(folder, 'chart.html'), '<p>a</p>')
|
||||
await chmod(join(folder, 'chart.html'), 0o000)
|
||||
try {
|
||||
const failure = await readNativeChatVisualFile(folder, 'chart.html').then(
|
||||
() => null,
|
||||
(error: unknown) => error
|
||||
)
|
||||
// Root bypasses mode bits, so assert refusal only when the read fails.
|
||||
if (failure !== null) {
|
||||
expect(String(failure)).toContain('visual_read_failed:EACCES')
|
||||
expect(String(failure)).not.toContain(stateDirectory)
|
||||
}
|
||||
} finally {
|
||||
await chmod(join(folder, 'chart.html'), 0o644)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const {
|
||||
initDaemonPtyProviderMock,
|
||||
disconnectDaemonMock,
|
||||
shutdownDaemonMock,
|
||||
daemonOwnsFreshPersistentPtysMock,
|
||||
readDaemonPidRecordMock
|
||||
} = vi.hoisted(() => ({
|
||||
initDaemonPtyProviderMock: vi.fn<(signal?: unknown, options?: unknown) => Promise<void>>(),
|
||||
disconnectDaemonMock: vi.fn<() => Promise<void>>(),
|
||||
shutdownDaemonMock: vi.fn<() => Promise<void>>(),
|
||||
daemonOwnsFreshPersistentPtysMock: vi.fn<() => boolean>(),
|
||||
readDaemonPidRecordMock: vi.fn<() => { pid: number } | null>()
|
||||
}))
|
||||
|
||||
vi.mock('../daemon/daemon-provider-init', () => ({
|
||||
initDaemonPtyProvider: initDaemonPtyProviderMock
|
||||
}))
|
||||
vi.mock('../daemon/daemon-provider-state', () => ({
|
||||
disconnectDaemon: disconnectDaemonMock,
|
||||
shutdownDaemon: shutdownDaemonMock,
|
||||
daemonOwnsFreshPersistentPtys: daemonOwnsFreshPersistentPtysMock,
|
||||
readDaemonPidRecord: readDaemonPidRecordMock
|
||||
}))
|
||||
|
||||
const { startOrcadDaemon, stopOrcadDaemon } = await import('./orcad-daemon-supervision')
|
||||
|
||||
beforeEach(() => {
|
||||
initDaemonPtyProviderMock.mockResolvedValue()
|
||||
disconnectDaemonMock.mockResolvedValue()
|
||||
shutdownDaemonMock.mockResolvedValue()
|
||||
daemonOwnsFreshPersistentPtysMock.mockReturnValue(true)
|
||||
readDaemonPidRecordMock.mockReturnValue({ pid: 4242 })
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('startOrcadDaemon', () => {
|
||||
it('reports live with the daemon pid once the provider is installed', async () => {
|
||||
await expect(startOrcadDaemon()).resolves.toEqual({ state: 'live', pid: 4242 })
|
||||
})
|
||||
|
||||
it('does not arm the macOS login-session death watch', async () => {
|
||||
await startOrcadDaemon()
|
||||
expect(initDaemonPtyProviderMock).toHaveBeenCalledWith(undefined, {
|
||||
macosLoginSessionWatch: false,
|
||||
recycleStaleDaemonOnEveryPlatform: true,
|
||||
spawnAdmission: 'enforce'
|
||||
})
|
||||
})
|
||||
|
||||
it('gives a cold Windows daemon a longer startup budget', async () => {
|
||||
await startOrcadDaemon('win32')
|
||||
expect(initDaemonPtyProviderMock).toHaveBeenCalledWith(undefined, {
|
||||
macosLoginSessionWatch: false,
|
||||
recycleStaleDaemonOnEveryPlatform: true,
|
||||
spawnAdmission: 'enforce',
|
||||
startupTimeoutMs: 30_000
|
||||
})
|
||||
})
|
||||
|
||||
it('retries the daemon spawn once before falling back to in-process terminals', async () => {
|
||||
initDaemonPtyProviderMock.mockRejectedValueOnce(new Error('Daemon startup timed out'))
|
||||
await expect(startOrcadDaemon()).resolves.toEqual({ state: 'live', pid: 4242 })
|
||||
expect(initDaemonPtyProviderMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('reports degraded when fresh terminals would fall back to the local provider', async () => {
|
||||
daemonOwnsFreshPersistentPtysMock.mockReturnValue(false)
|
||||
const result = await startOrcadDaemon()
|
||||
expect(result.state).toBe('degraded')
|
||||
})
|
||||
|
||||
it('fails open when the daemon cannot start at all', async () => {
|
||||
initDaemonPtyProviderMock.mockRejectedValue(new Error('node-pty is missing'))
|
||||
daemonOwnsFreshPersistentPtysMock.mockReturnValue(false)
|
||||
await expect(startOrcadDaemon()).resolves.toEqual({
|
||||
state: 'unavailable',
|
||||
reason: 'node-pty is missing'
|
||||
})
|
||||
expect(initDaemonPtyProviderMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('stopOrcadDaemon', () => {
|
||||
it('disconnects and never shuts the daemon down', async () => {
|
||||
await stopOrcadDaemon()
|
||||
expect(disconnectDaemonMock).toHaveBeenCalledTimes(1)
|
||||
expect(shutdownDaemonMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -40,38 +40,6 @@ describe('prepareWslMoveHost (A1)', () => {
|
||||
expect(stopped.add).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('adds a host for a running bridge distro, or connects the one it has', async () => {
|
||||
const bridge = deps()
|
||||
expect(await prepareWslMoveHost(bridge, 'ubuntu')).toBe('ready')
|
||||
expect(bridge.add).toHaveBeenCalledWith('ubuntu')
|
||||
const added = deps({ hasHost: () => true })
|
||||
expect(await prepareWslMoveHost(added, 'Ubuntu')).toBe('ready')
|
||||
expect(added.connect).toHaveBeenCalled()
|
||||
expect(added.add).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports a refused add or failed connect as failed', async () => {
|
||||
const refused = deps({
|
||||
add: async () => ({ ok: false, kind: 'failed', message: 'nope' })
|
||||
})
|
||||
expect(await prepareWslMoveHost(refused, 'Ubuntu')).toBe('failed')
|
||||
const broken = deps({
|
||||
hasHost: () => true,
|
||||
connect: async () => {
|
||||
throw new Error('pairing')
|
||||
}
|
||||
})
|
||||
expect(await prepareWslMoveHost(broken, 'Ubuntu')).toBe('failed')
|
||||
})
|
||||
|
||||
// E11 (#33843): a host whose Remove is pending is never connected or added.
|
||||
it('never connects or adds a host whose Remove is pending', async () => {
|
||||
const pending = deps({ hasHost: () => true, removalPending: () => true })
|
||||
expect(await prepareWslMoveHost(pending, 'Ubuntu')).toBe('failed')
|
||||
expect(pending.connect).not.toHaveBeenCalled()
|
||||
expect(pending.add).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('re-reads the pending Remove after the running-distro read', async () => {
|
||||
let removing = false
|
||||
const racing = deps({
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import wslMoveAgentModelUI from '../../../shared/__fixtures__/wsl-move-agent-model-ui.json'
|
||||
import { projectWslMoveUi } from './wsl-move-session-projection'
|
||||
|
||||
import { toRuntimeExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host'
|
||||
import type { WorkspaceCleanupDismissal } from '../../../shared/workspace-cleanup'
|
||||
import { wslMoveCutoverFixture } from '../__fixtures__/wsl-mover/wsl-move-cutover-fixture'
|
||||
@@ -135,22 +134,6 @@ describe('WSL move UI routing rewrite', () => {
|
||||
}
|
||||
)
|
||||
|
||||
it('preserves global model visibility in the desktop snapshot consumed by the renderer', () => {
|
||||
const desktop = wslMoveAgentModelUI.desktopBeforeMove
|
||||
const projected = projectWslMoveUi(
|
||||
desktop,
|
||||
{},
|
||||
(owner) => !!owner && scope.inScope(owner),
|
||||
() => true
|
||||
)
|
||||
expect(projected).not.toHaveProperty('showAgentModels')
|
||||
expect(projected).toEqual(wslMoveAgentModelUI.projectedProjectUI)
|
||||
const updates = rewriteWslMoveUiRouting(desktop, scope)
|
||||
expect(updates).not.toHaveProperty('showAgentModels')
|
||||
// The renderer consumes this exact snapshot; changes to production output must update the contract.
|
||||
expect({ ...desktop, ...updates }).toEqual(wslMoveAgentModelUI.desktopAfterMove)
|
||||
})
|
||||
|
||||
it("copies only the moved project's rows to the host's form, keeping the local ones", () => {
|
||||
const ui = profileUi()
|
||||
const updates = rewriteWslMoveUiRouting(ui, scope)
|
||||
@@ -247,47 +230,6 @@ describe('WSL move UI routing rewrite', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('adds the host wherever local is shown, and never removes local', () => {
|
||||
const updates = rewriteWslMoveUiRouting(profileUi(), scope)
|
||||
|
||||
// The legacy `local` scope resolves to a list, so the host joins it there.
|
||||
expect(updates.visibleWorkspaceHostIds).toEqual(['local', HOST])
|
||||
expect(updates.workspaceHostScope).toBeUndefined()
|
||||
expect(updates.agentsVisibleHostIds).toEqual([SSH, 'local', HOST])
|
||||
expect(updates.workspaceHostOrder).toEqual(['local', HOST, SSH])
|
||||
})
|
||||
|
||||
it('leaves host filters that do not show local, or show all hosts, alone', () => {
|
||||
const updates = rewriteWslMoveUiRouting(
|
||||
{
|
||||
...profileUi(),
|
||||
workspaceHostScope: 'all',
|
||||
visibleWorkspaceHostIds: null,
|
||||
agentsVisibleHostIds: [SSH],
|
||||
workspaceHostOrder: undefined
|
||||
},
|
||||
scope
|
||||
)
|
||||
|
||||
expect(updates.visibleWorkspaceHostIds).toBeUndefined()
|
||||
expect(updates.agentsVisibleHostIds).toBeUndefined()
|
||||
expect(updates.workspaceHostOrder).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps the local setup-prompt dismissal and lineage group beside the host ones', () => {
|
||||
const ui = profileUi()
|
||||
const updates = rewriteWslMoveUiRouting(ui, scope)
|
||||
|
||||
expect(updates.setupScriptPromptDismissedRepoIds).toEqual([
|
||||
...(ui.setupScriptPromptDismissedRepoIds ?? []),
|
||||
`generation-v1:${HOST}\0repo-a`
|
||||
])
|
||||
expect(updates.collapsedGroups).toEqual([
|
||||
...ui.collapsedGroups,
|
||||
`lineage:${HOST}|${MOVED_ON_HOST}`
|
||||
])
|
||||
})
|
||||
|
||||
it('carries host and folder project collapse keys only for the moved project', () => {
|
||||
const project = 'project:github:org/app'
|
||||
const host = `${project}::host:local::local::wsl:ubuntu`
|
||||
@@ -338,16 +280,4 @@ describe('WSL move UI routing rewrite', () => {
|
||||
|
||||
expect(rewriteWslMoveUiRouting(first, scope)).toEqual({})
|
||||
})
|
||||
|
||||
it('changes nothing for a UI that never named the moved project', () => {
|
||||
const ui: WslMoveUiRoutingState = {
|
||||
lastActiveWorktreeId: WINDOWS,
|
||||
showDotfilesByWorktree: { [SAME_DISTRO]: true },
|
||||
collapsedGroups: [`lineage:local|${WINDOWS}`],
|
||||
manualRepoOrder: [{ hostId: 'local', repoId: 'repo-win' }],
|
||||
agentsVisibleHostIds: null
|
||||
}
|
||||
|
||||
expect(rewriteWslMoveUiRouting(ui, scope)).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -4,7 +4,7 @@ import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { hashPluginTree } from './plugin-content-hash'
|
||||
import { installPluginFromLocalPath, readPluginLockfile } from './installation/plugin-install'
|
||||
import { bootstrapBundledPlugins, resolveBundledPluginRoot } from './plugin-bundled-bootstrap'
|
||||
import { bootstrapBundledPlugins } from './plugin-bundled-bootstrap'
|
||||
|
||||
const roots: string[] = []
|
||||
|
||||
@@ -53,30 +53,6 @@ afterEach(async () => {
|
||||
})
|
||||
|
||||
describe('bundled plugin bootstrap', () => {
|
||||
it('installs release-indexed content once and keeps unchanged startup work bounded', async () => {
|
||||
const root = await tempRoot('orca-bundled-resources-')
|
||||
const userDataPath = await tempRoot('orca-bundled-user-data-')
|
||||
const bundle = await writeBundle(root)
|
||||
await writeIndex(root, bundle.path, bundle.hash)
|
||||
|
||||
await expect(
|
||||
bootstrapBundledPlugins({ root, userDataPath, hostVersion: '1.4.0' })
|
||||
).resolves.toEqual({
|
||||
installed: ['stablyai.orca-skills'],
|
||||
unchanged: [],
|
||||
retired: [],
|
||||
errors: []
|
||||
})
|
||||
await expect(
|
||||
bootstrapBundledPlugins({ root, userDataPath, hostVersion: '1.4.0' })
|
||||
).resolves.toEqual({
|
||||
installed: [],
|
||||
unchanged: ['stablyai.orca-skills'],
|
||||
retired: [],
|
||||
errors: []
|
||||
})
|
||||
})
|
||||
|
||||
it('publishes an updated immutable bundle only when the indexed hash matches', async () => {
|
||||
const root = await tempRoot('orca-bundled-resources-')
|
||||
const userDataPath = await tempRoot('orca-bundled-user-data-')
|
||||
@@ -198,21 +174,4 @@ describe('bundled plugin bootstrap', () => {
|
||||
expect(result.errors[0]?.error).toContain('does not match its release index')
|
||||
expect((await readPluginLockfile(join(userDataPath, 'plugins'))).plugins).toEqual({})
|
||||
})
|
||||
|
||||
it('resolves packaged and development resource roots without platform separators', () => {
|
||||
expect(
|
||||
resolveBundledPluginRoot({
|
||||
isPackaged: true,
|
||||
resourcesPath: join('app', 'resources'),
|
||||
appPath: join('repo', 'app')
|
||||
})
|
||||
).toBe(join('app', 'resources', 'plugins', 'launch'))
|
||||
expect(
|
||||
resolveBundledPluginRoot({
|
||||
isPackaged: false,
|
||||
resourcesPath: join('app', 'resources'),
|
||||
appPath: join('repo', 'app')
|
||||
})
|
||||
).toBe(join('repo', 'app', 'resources', 'plugins', 'launch'))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -64,46 +64,6 @@ describe('project repositories', () => {
|
||||
})
|
||||
|
||||
describe('installed plugin discovery identity', () => {
|
||||
it('requires a new review when an installed v2 worker has different bytes', async () => {
|
||||
const pluginsDir = await tempPluginsDir()
|
||||
const key = 'samples.worker'
|
||||
const discoverAt = async (hash: string) => {
|
||||
const versionDir = join(pluginsDir, key, hash)
|
||||
await mkdir(versionDir, { recursive: true })
|
||||
await writeFile(join(pluginsDir, key, 'current'), hash)
|
||||
await writeFile(join(versionDir, 'main.mjs'), 'export default () => {}')
|
||||
await writeFile(
|
||||
join(versionDir, 'orca-plugin.json'),
|
||||
JSON.stringify({
|
||||
manifestVersion: 2,
|
||||
execution: 'trusted-worker',
|
||||
id: 'worker',
|
||||
publisher: 'samples',
|
||||
name: 'Worker',
|
||||
version: '1.0.0',
|
||||
engines: { orca: `>=${PLUGIN_SCHEMA_NEWEST_SINCE}` },
|
||||
pluginApi: 1,
|
||||
main: 'main.mjs'
|
||||
})
|
||||
)
|
||||
const [plugin] = await discoverPlugins({
|
||||
pluginsDir,
|
||||
devPluginPaths: [],
|
||||
hostVersion: PLUGIN_SCHEMA_NEWEST_SINCE
|
||||
})
|
||||
if (!plugin || isInvalidDiscoveredPlugin(plugin)) {
|
||||
throw new Error('expected a valid plugin')
|
||||
}
|
||||
return plugin
|
||||
}
|
||||
|
||||
const approved = await discoverAt('a'.repeat(64))
|
||||
const updated = await discoverAt('b'.repeat(64))
|
||||
|
||||
expect(updated.consentContentHash).toBe('b'.repeat(64))
|
||||
expect(updated.consentFingerprint).not.toBe(approved.consentFingerprint)
|
||||
})
|
||||
|
||||
it('keeps the install directory identity when a manifest is invalid or mismatched', async () => {
|
||||
const pluginsDir = await tempPluginsDir()
|
||||
const installedKey = 'samples.expected'
|
||||
@@ -133,34 +93,6 @@ describe('installed plugin discovery identity', () => {
|
||||
expect(plugin && 'error' in plugin ? plugin.error : '').toContain('does not match')
|
||||
})
|
||||
|
||||
it('names the version gap when a plugin for a newer Orca uses fields this build lacks', async () => {
|
||||
const pluginsDir = await tempPluginsDir()
|
||||
const hash = 'b'.repeat(64)
|
||||
const versionDir = join(pluginsDir, 'acme.future', hash)
|
||||
await mkdir(versionDir, { recursive: true })
|
||||
await writeFile(join(pluginsDir, 'acme.future', 'current'), hash)
|
||||
await writeFile(
|
||||
join(versionDir, 'orca-plugin.json'),
|
||||
JSON.stringify({
|
||||
manifestVersion: 2,
|
||||
execution: 'data',
|
||||
id: 'future',
|
||||
publisher: 'acme',
|
||||
name: 'Future',
|
||||
version: '1.0.0',
|
||||
engines: { orca: '>=9.0.0' },
|
||||
pluginApi: 1,
|
||||
contributes: { widgets: [{ id: 'clock' }] }
|
||||
})
|
||||
)
|
||||
|
||||
const [plugin] = await discoverPlugins({ pluginsDir, devPluginPaths: [], hostVersion: '1.4.0' })
|
||||
|
||||
expect(plugin && 'error' in plugin ? plugin.error : '').toBe(
|
||||
'requires Orca >=9.0.0 (this is 1.4.0)'
|
||||
)
|
||||
})
|
||||
|
||||
// Regression: Excalidraw 1.0.0 as installed from the catalog before the format 2 floor moved.
|
||||
it('loads an installed manifest whose engines floor predates its fields, but not a dev copy', async () => {
|
||||
const pluginsDir = await tempPluginsDir()
|
||||
@@ -215,17 +147,6 @@ describe('installed plugin discovery identity', () => {
|
||||
expect(old && 'error' in old ? old.error : '').toBe('requires Orca >=1.4.244 (this is 1.4.200)')
|
||||
})
|
||||
|
||||
it('keeps a removable qualified identity when the current pointer is missing', async () => {
|
||||
const pluginsDir = await tempPluginsDir()
|
||||
const installedKey = 'samples.broken'
|
||||
await mkdir(join(pluginsDir, installedKey), { recursive: true })
|
||||
|
||||
const [plugin] = await discoverPlugins({ pluginsDir, devPluginPaths: [], hostVersion: '1.4.0' })
|
||||
|
||||
expect(plugin && isInvalidDiscoveredPlugin(plugin)).toBe(true)
|
||||
expect(plugin?.pluginKey).toBe(installedKey)
|
||||
})
|
||||
|
||||
it('rejects an oversized current pointer without an unbounded startup read', async () => {
|
||||
const pluginsDir = await tempPluginsDir()
|
||||
const installedKey = 'samples.broken'
|
||||
|
||||
@@ -169,15 +169,3 @@ it('waits for removal during service disposal and preserves history until succes
|
||||
}
|
||||
expect(service.getLogs(key)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('preserves installed crash history while cancelling the existing restart backoff', async () => {
|
||||
const { service, install } = await createUninstallFixture()
|
||||
const key = await install('crash')
|
||||
const child = latestUninstallWorker()
|
||||
child.connected = false
|
||||
child.emit('exit', 1)
|
||||
expect(latestPluginLog(service, key).line).toContain('exited unexpectedly')
|
||||
await service.deactivatePlugin(key)
|
||||
expect(service.findValidPlugin(key)).not.toBeNull()
|
||||
expect(service.getLogs(key)).toHaveLength(200)
|
||||
})
|
||||
|
||||
@@ -29,127 +29,6 @@ describePosix('live zsh subprocess tests', () => {
|
||||
rmSync(userDataPath, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('discovers ZDOTDIR when launched inside tmux', async () => {
|
||||
const xdgZshDir = join(testHome, '.config', 'zsh')
|
||||
mkdirSync(xdgZshDir, { recursive: true })
|
||||
writeFileSync(join(testHome, '.zshenv'), `export ZDOTDIR="${xdgZshDir}"\n`)
|
||||
|
||||
const { getShellReadyLaunchConfig } = await importFreshLocalPtyShellReady()
|
||||
const config = getShellReadyLaunchConfig('/bin/zsh')
|
||||
|
||||
const cleanEnv: Record<string, string | undefined> = {
|
||||
...process.env,
|
||||
HOME: testHome,
|
||||
TMUX: '/tmp/tmux-501/default,12345,0',
|
||||
TMUX_PANE: '%0'
|
||||
}
|
||||
delete cleanEnv.ZDOTDIR
|
||||
delete cleanEnv.ORCA_ORIG_ZDOTDIR
|
||||
cleanEnv.ZDOTDIR = config.env.ZDOTDIR
|
||||
|
||||
const result = spawnSync('zsh', ['-c', 'echo "ZDOTDIR=${ZDOTDIR}"'], {
|
||||
env: cleanEnv as NodeJS.ProcessEnv,
|
||||
encoding: 'utf8'
|
||||
})
|
||||
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout).toContain(`ZDOTDIR=${xdgZshDir}`)
|
||||
})
|
||||
|
||||
it('discovers ZDOTDIR when launched from SSH session', async () => {
|
||||
const xdgZshDir = join(testHome, '.config', 'zsh')
|
||||
mkdirSync(xdgZshDir, { recursive: true })
|
||||
writeFileSync(join(testHome, '.zshenv'), `export ZDOTDIR="${xdgZshDir}"\n`)
|
||||
|
||||
const { getShellReadyLaunchConfig } = await importFreshLocalPtyShellReady()
|
||||
const config = getShellReadyLaunchConfig('/bin/zsh')
|
||||
|
||||
const cleanEnv: Record<string, string | undefined> = {
|
||||
...process.env,
|
||||
HOME: testHome,
|
||||
SSH_CONNECTION: '10.0.0.1 12345 10.0.0.2 22',
|
||||
SSH_CLIENT: '10.0.0.1 12345 22',
|
||||
LC_CTYPE: 'C.UTF-8'
|
||||
}
|
||||
delete cleanEnv.ZDOTDIR
|
||||
delete cleanEnv.ORCA_ORIG_ZDOTDIR
|
||||
cleanEnv.ZDOTDIR = config.env.ZDOTDIR
|
||||
|
||||
const result = spawnSync('zsh', ['-c', 'echo "ZDOTDIR=${ZDOTDIR}"'], {
|
||||
env: cleanEnv as NodeJS.ProcessEnv,
|
||||
encoding: 'utf8'
|
||||
})
|
||||
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout).toContain(`ZDOTDIR=${xdgZshDir}`)
|
||||
})
|
||||
|
||||
it('handles sudo -E where HOME and ZDOTDIR mismatch', async () => {
|
||||
// Inherited ZDOTDIR counts as user configuration only when it contains a startup file.
|
||||
const userZdotdir = join(testHome, '.config', 'zsh')
|
||||
mkdirSync(userZdotdir, { recursive: true })
|
||||
writeFileSync(join(userZdotdir, '.zshrc'), '')
|
||||
|
||||
const previousZdotdir = process.env.ZDOTDIR
|
||||
const previousHome = process.env.HOME
|
||||
process.env.ZDOTDIR = userZdotdir
|
||||
process.env.HOME = '/root' // sudo changed HOME
|
||||
|
||||
try {
|
||||
const { getShellReadyLaunchConfig } = await importFreshLocalPtyShellReady()
|
||||
const config = getShellReadyLaunchConfig('/bin/zsh')
|
||||
|
||||
expect(config.env.ORCA_ORIG_ZDOTDIR).toBe(userZdotdir)
|
||||
} finally {
|
||||
if (previousZdotdir === undefined) {
|
||||
delete process.env.ZDOTDIR
|
||||
} else {
|
||||
process.env.ZDOTDIR = previousZdotdir
|
||||
}
|
||||
if (previousHome === undefined) {
|
||||
delete process.env.HOME
|
||||
} else {
|
||||
process.env.HOME = previousHome
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('re-discovers ZDOTDIR despite stale ORCA_ORIG_ZDOTDIR from previous session', async () => {
|
||||
const currentZdotdir = join(testHome, '.config', 'zsh-current')
|
||||
mkdirSync(currentZdotdir, { recursive: true })
|
||||
writeFileSync(join(testHome, '.zshenv'), `export ZDOTDIR="${currentZdotdir}"\n`)
|
||||
|
||||
const previousOrcaZdotdir = process.env.ORCA_ORIG_ZDOTDIR
|
||||
process.env.ORCA_ORIG_ZDOTDIR = '/opt/orca-old/shell-ready/zsh' // stale wrapper path
|
||||
|
||||
try {
|
||||
const { getShellReadyLaunchConfig } = await importFreshLocalPtyShellReady()
|
||||
const config = getShellReadyLaunchConfig('/bin/zsh')
|
||||
|
||||
const cleanEnv: Record<string, string | undefined> = {
|
||||
...process.env,
|
||||
HOME: testHome,
|
||||
ORCA_ORIG_ZDOTDIR: '/opt/orca-old/shell-ready/zsh'
|
||||
}
|
||||
delete cleanEnv.ZDOTDIR
|
||||
cleanEnv.ZDOTDIR = config.env.ZDOTDIR
|
||||
|
||||
const result = spawnSync('zsh', ['-c', 'echo "ZDOTDIR=${ZDOTDIR}"'], {
|
||||
env: cleanEnv as NodeJS.ProcessEnv,
|
||||
encoding: 'utf8'
|
||||
})
|
||||
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout).toContain(`ZDOTDIR=${currentZdotdir}`)
|
||||
} finally {
|
||||
if (previousOrcaZdotdir === undefined) {
|
||||
delete process.env.ORCA_ORIG_ZDOTDIR
|
||||
} else {
|
||||
process.env.ORCA_ORIG_ZDOTDIR = previousOrcaZdotdir
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('prioritizes fresh discovery over inherited ORCA_ORIG_ZDOTDIR', async () => {
|
||||
const freshZdotdir = join(testHome, '.config', 'zsh-updated')
|
||||
mkdirSync(freshZdotdir, { recursive: true })
|
||||
|
||||
@@ -19,15 +19,6 @@ describe('PTY provider process inspection', () => {
|
||||
expect(provider.getForegroundProcess).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('preserves a completion-sensitive provider failure', async () => {
|
||||
const failure = new Error('daemon unavailable')
|
||||
const inspectProcess = vi.fn().mockRejectedValue(failure)
|
||||
const provider = { inspectProcess } as unknown as IPtyProvider
|
||||
|
||||
await expect(inspectPtyProviderProcess(provider, 'pty-1')).rejects.toBe(failure)
|
||||
expect(inspectProcess).toHaveBeenCalledExactlyOnceWith('pty-1')
|
||||
})
|
||||
|
||||
it('returns client-only unverifiable to the renderer when a stale PTY is gone', async () => {
|
||||
const provider = {
|
||||
hasPty: vi.fn(() => false)
|
||||
@@ -62,31 +53,4 @@ describe('PTY provider process inspection', () => {
|
||||
reason: 'transport_loss'
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves a client-only unverifiable inspection result', async () => {
|
||||
const inspection = {
|
||||
foregroundProcess: null,
|
||||
hasChildProcesses: false,
|
||||
verdict: 'unverifiable' as const,
|
||||
reason: 'transport_loss' as const
|
||||
}
|
||||
const inspectProcess = vi.fn().mockResolvedValue(inspection)
|
||||
const provider = { inspectProcess } as unknown as IPtyProvider
|
||||
|
||||
await expect(inspectPtyProviderProcess(provider, 'pty-1')).resolves.toEqual(inspection)
|
||||
})
|
||||
|
||||
it('falls back to the existing provider process APIs', async () => {
|
||||
const getForegroundProcess = vi.fn().mockResolvedValue('codex')
|
||||
const hasChildProcesses = vi.fn().mockResolvedValue(true)
|
||||
const provider = {
|
||||
getForegroundProcess,
|
||||
hasChildProcesses
|
||||
} as Pick<IPtyProvider, 'getForegroundProcess' | 'hasChildProcesses'> as IPtyProvider
|
||||
|
||||
await expect(inspectPtyProviderProcess(provider, 'pty-1')).resolves.toEqual({
|
||||
foregroundProcess: 'codex',
|
||||
hasChildProcesses: true
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -58,11 +58,6 @@ describe('windows process rows', () => {
|
||||
|
||||
const scanCount = (): number => getAllProcessesMock.mock.calls.length
|
||||
|
||||
it('walks descendants from the native snapshot', async () => {
|
||||
const candidates = await queryWindowsProcessDescendants(100)
|
||||
expect(candidates?.[0]?.pid).toBe(200)
|
||||
})
|
||||
|
||||
it('rejects a snapshot that does not contain the querying process', async () => {
|
||||
// A missing self PID invalidates the table; false empty evidence could authorize teardown.
|
||||
getAllProcessesMock.mockImplementation((cb: (rows: unknown) => void) => {
|
||||
@@ -98,15 +93,6 @@ describe('windows process rows', () => {
|
||||
expect(rows[31]?.map((row) => row.pid)).toEqual([200])
|
||||
})
|
||||
|
||||
it('never answers from the TTL cache, which can predate the recycle it detects', async () => {
|
||||
await queryWindowsProcessDescendants(100)
|
||||
expect(scanCount()).toBe(1)
|
||||
|
||||
await queryWindowsProcessDescendants(100, { fresh: true })
|
||||
|
||||
expect(scanCount()).toBe(2)
|
||||
})
|
||||
|
||||
it('never answers the ancestry links from the identity TTL cache either', async () => {
|
||||
// Ancestry uses a separate identity TTL cache; fresh teardown must bypass that cache too.
|
||||
await readWindowsProcessIdentityTable()
|
||||
|
||||
@@ -47,13 +47,6 @@ async function retiredPty(
|
||||
const describeOnPosix = process.platform === 'win32' ? describe.skip : describe
|
||||
|
||||
describeOnPosix('node-pty master fd retirement', () => {
|
||||
it('invalidates the descriptor once it gives up the handle', async () => {
|
||||
const { term, spawnFd } = await retiredPty()
|
||||
|
||||
expect(spawnFd).toBeGreaterThanOrEqual(0)
|
||||
expect(masterFd(term)).toBe(-1)
|
||||
}, 15000)
|
||||
|
||||
it('answers a resize past retirement without issuing the ioctl', async () => {
|
||||
const { term } = await retiredPty()
|
||||
|
||||
@@ -71,12 +64,6 @@ describeOnPosix('node-pty master fd retirement', () => {
|
||||
writeStream(term).write('x')
|
||||
expect(writeStream(term)._writeQueue).toHaveLength(0)
|
||||
}, 15000)
|
||||
|
||||
it('names the spawn file rather than tcgetpgrp on a retired descriptor', async () => {
|
||||
const { term } = await retiredPty()
|
||||
|
||||
expect(term.process).toBe(POSIX_SHELL)
|
||||
}, 15000)
|
||||
})
|
||||
|
||||
// Linux reuses the lowest free fd; await every fixture exit so leaked descriptors cannot invalidate the next case.
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
cursorSessionCookie,
|
||||
isCursorSessionTokenExpired,
|
||||
parseCursorSessionToken
|
||||
} from './cursor-session-token'
|
||||
import { cursorSessionCookie, parseCursorSessionToken } from './cursor-session-token'
|
||||
|
||||
type JwtSegment = Record<string, unknown>
|
||||
|
||||
@@ -31,27 +27,6 @@ describe('parseCursorSessionToken', () => {
|
||||
expect(parseCursorSessionToken('not-a-jwt')).toBeNull()
|
||||
expect(parseCursorSessionToken('a.!!!.c')).toBeNull()
|
||||
})
|
||||
|
||||
it('leaves expiry null when the token omits exp', () => {
|
||||
expect(parseCursorSessionToken(jwt({ sub: 'auth0|user_1' }))?.expiresAtMs).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('isCursorSessionTokenExpired', () => {
|
||||
const token = parseCursorSessionToken(jwt({ sub: 'auth0|user_1', exp: 2_000 }))
|
||||
|
||||
it('reports a lapsed session', () => {
|
||||
expect(isCursorSessionTokenExpired(token!, 2_000_001)).toBe(true)
|
||||
})
|
||||
|
||||
it('reports a live session', () => {
|
||||
expect(isCursorSessionTokenExpired(token!, 1_999_999)).toBe(false)
|
||||
})
|
||||
|
||||
it('never expires a token with no exp claim', () => {
|
||||
const noExpiry = parseCursorSessionToken(jwt({ sub: 'auth0|user_1' }))
|
||||
expect(isCursorSessionTokenExpired(noExpiry!, Number.MAX_SAFE_INTEGER)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('cursorSessionCookie', () => {
|
||||
|
||||
@@ -102,17 +102,6 @@ describe('git remote identity enrichment under a WSL move', () => {
|
||||
})
|
||||
|
||||
describe('fork upstream backfill under a WSL move', () => {
|
||||
it('leaves the moving repo unset for a later run and fills the rest', async () => {
|
||||
const store = createStore()
|
||||
store.addRepo(repo(MOVING))
|
||||
store.addRepo(repo(STAYING))
|
||||
|
||||
await new RuntimeRepositoryForkBackfill(() => store, vi.fn()).run()
|
||||
|
||||
expect(store.getRepo(MOVING)?.upstream).toBeUndefined()
|
||||
expect(store.getRepo(STAYING)?.upstream).toEqual({ owner: 'acme', repo: 'app' })
|
||||
})
|
||||
|
||||
it('fills the host row, not the hidden local row with the same id', async () => {
|
||||
seedWslMoveCutover(testState.dir, cutover('move-1', 'destination-committed'))
|
||||
const store = createStore()
|
||||
|
||||
@@ -25,14 +25,6 @@ describe('probeGitRemoteIdentity', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('settles on no-remote when git answers with nothing usable', async () => {
|
||||
vi.mocked(gitExecFileAsync).mockResolvedValue({ stdout: '', stderr: '' })
|
||||
|
||||
await expect(probeGitRemoteIdentity('/repos/orca', 'local')).resolves.toEqual({
|
||||
status: 'no-remote'
|
||||
})
|
||||
})
|
||||
|
||||
it('reports unavailable for an SSH host', async () => {
|
||||
await expect(probeGitRemoteIdentity('/repos/orca', 'ssh:builder')).resolves.toEqual({
|
||||
status: 'unavailable'
|
||||
@@ -46,50 +38,4 @@ describe('probeGitRemoteIdentity', () => {
|
||||
})
|
||||
expect(gitExecFileAsync).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports unavailable when the local git command fails', async () => {
|
||||
vi.mocked(gitExecFileAsync).mockRejectedValue(new Error('not a git repository'))
|
||||
|
||||
await expect(probeGitRemoteIdentity('/repos/orca', 'local')).resolves.toEqual({
|
||||
status: 'unavailable'
|
||||
})
|
||||
})
|
||||
|
||||
it('bounds the local probe with a deadline and forwards the caller signal', async () => {
|
||||
vi.mocked(gitExecFileAsync).mockResolvedValue({ stdout: gitlabRemote, stderr: '' })
|
||||
const controller = new AbortController()
|
||||
|
||||
await probeGitRemoteIdentity('/repos/orca', 'local', { signal: controller.signal })
|
||||
|
||||
expect(gitExecFileAsync).toHaveBeenCalledWith(
|
||||
['remote', '-v'],
|
||||
expect.objectContaining({
|
||||
cwd: '/repos/orca',
|
||||
timeout: expect.any(Number),
|
||||
signal: controller.signal
|
||||
})
|
||||
)
|
||||
const [, options] = vi.mocked(gitExecFileAsync).mock.calls[0]
|
||||
expect(options.timeout).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('maps a timed-out local probe to unavailable, never no-remote', async () => {
|
||||
vi.mocked(gitExecFileAsync).mockRejectedValue(new Error('git timed out.'))
|
||||
|
||||
await expect(probeGitRemoteIdentity('/repos/orca', 'local')).resolves.toEqual({
|
||||
status: 'unavailable'
|
||||
})
|
||||
})
|
||||
|
||||
it('maps an aborted probe to unavailable, never no-remote', async () => {
|
||||
const abortError = new Error('The operation was aborted')
|
||||
abortError.name = 'AbortError'
|
||||
vi.mocked(gitExecFileAsync).mockRejectedValue(abortError)
|
||||
const controller = new AbortController()
|
||||
controller.abort()
|
||||
|
||||
await expect(
|
||||
probeGitRemoteIdentity('/repos/orca', 'local', { signal: controller.signal })
|
||||
).resolves.toEqual({ status: 'unavailable' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const isOnBatteryPowerMock = vi.hoisted(() => vi.fn(() => false))
|
||||
const hasPendingPreparationsMock = vi.hoisted(() => vi.fn(() => false))
|
||||
const hasRemovalsInFlightMock = vi.hoisted(() => vi.fn(() => false))
|
||||
const setProbeMock = vi.hoisted(() => vi.fn())
|
||||
const disposeMock = vi.hoisted(() => vi.fn(async () => {}))
|
||||
const postponeMock = vi.hoisted(() => vi.fn())
|
||||
const powerListeners = vi.hoisted(() => new Map<string, () => void>())
|
||||
const appListeners = vi.hoisted(() => new Map<string, () => void>())
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: {
|
||||
on: (event: string, listener: () => void) => appListeners.set(event, listener),
|
||||
off: (event: string) => appListeners.delete(event)
|
||||
},
|
||||
powerMonitor: {
|
||||
isOnBatteryPower: isOnBatteryPowerMock,
|
||||
on: (event: string, listener: () => void) => powerListeners.set(event, listener),
|
||||
off: (event: string) => powerListeners.delete(event)
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('./worktree-create-preparation', () => ({
|
||||
hasPendingWorktreeCreatePreparations: hasPendingPreparationsMock
|
||||
}))
|
||||
|
||||
vi.mock('./ipc/worktrees/worktree-ipc-context', () => ({
|
||||
hasWorktreeRemovalsInFlight: hasRemovalsInFlightMock
|
||||
}))
|
||||
|
||||
vi.mock('./git/local-repo-ref-maintenance', () => ({
|
||||
setRepoMaintenanceActivityProbe: setProbeMock,
|
||||
disposeLocalRepoRefMaintenance: disposeMock,
|
||||
postponeRepoRefMaintenance: postponeMock
|
||||
}))
|
||||
|
||||
import { installRepoMaintenanceIdleGate } from './repo-maintenance-idle-gate'
|
||||
|
||||
function installProbe(
|
||||
overrides: Partial<{ isQuitting: () => boolean; getWorkingAgentCount: () => number }> = {}
|
||||
): { probe: () => boolean; uninstall: () => Promise<void> } {
|
||||
const uninstall = installRepoMaintenanceIdleGate({
|
||||
isQuitting: () => false,
|
||||
getWorkingAgentCount: () => 0,
|
||||
...overrides
|
||||
})
|
||||
return { probe: setProbeMock.mock.calls.at(-1)?.[0] as () => boolean, uninstall }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
isOnBatteryPowerMock.mockReturnValue(false)
|
||||
hasPendingPreparationsMock.mockReturnValue(false)
|
||||
hasRemovalsInFlightMock.mockReturnValue(false)
|
||||
postponeMock.mockClear()
|
||||
powerListeners.clear()
|
||||
appListeners.clear()
|
||||
setProbeMock.mockClear()
|
||||
disposeMock.mockClear()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('repo maintenance idle gate', () => {
|
||||
it('reports idle when nothing is happening', () => {
|
||||
expect(installProbe().probe()).toBe(false)
|
||||
})
|
||||
|
||||
it('vetoes while an agent is working', () => {
|
||||
expect(installProbe({ getWorkingAgentCount: () => 1 }).probe()).toBe(true)
|
||||
})
|
||||
|
||||
it('vetoes while a worktree create is prepared or in flight', () => {
|
||||
hasPendingPreparationsMock.mockReturnValue(true)
|
||||
|
||||
expect(installProbe().probe()).toBe(true)
|
||||
})
|
||||
|
||||
it('vetoes while a worktree removal is deleting refs', () => {
|
||||
hasRemovalsInFlightMock.mockReturnValue(true)
|
||||
|
||||
expect(installProbe().probe()).toBe(true)
|
||||
})
|
||||
|
||||
it('vetoes on battery power', () => {
|
||||
isOnBatteryPowerMock.mockReturnValue(true)
|
||||
|
||||
expect(installProbe().probe()).toBe(true)
|
||||
})
|
||||
|
||||
it('vetoes during shutdown', () => {
|
||||
expect(installProbe({ isQuitting: () => true }).probe()).toBe(true)
|
||||
})
|
||||
|
||||
it('treats an unavailable power API as not-on-battery', () => {
|
||||
isOnBatteryPowerMock.mockImplementation(() => {
|
||||
throw new Error('unsupported')
|
||||
})
|
||||
|
||||
expect(installProbe().probe()).toBe(false)
|
||||
})
|
||||
|
||||
it('pushes the next attempt out when the machine drops onto battery', () => {
|
||||
installProbe()
|
||||
|
||||
powerListeners.get('on-battery')?.()
|
||||
|
||||
expect(postponeMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('pushes the next attempt out when the user comes back to the window', () => {
|
||||
// A window left focused while the user is away fires no new focus event.
|
||||
installProbe()
|
||||
|
||||
appListeners.get('browser-window-focus')?.()
|
||||
|
||||
expect(postponeMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('cancels armed timers, unsubscribes both sources, and clears the probe when uninstalled', async () => {
|
||||
await installProbe().uninstall()
|
||||
|
||||
expect(disposeMock).toHaveBeenCalledTimes(1)
|
||||
expect(powerListeners.has('on-battery')).toBe(false)
|
||||
expect(appListeners.has('browser-window-focus')).toBe(false)
|
||||
expect(setProbeMock).toHaveBeenLastCalledWith(null)
|
||||
})
|
||||
})
|
||||
@@ -1,20 +1,11 @@
|
||||
import {
|
||||
chmodSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
realpathSync,
|
||||
rmSync,
|
||||
writeFileSync
|
||||
} from 'node:fs'
|
||||
import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
|
||||
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { runProcess } from '@orca/process-host'
|
||||
import { toBundledRipgrepPlatform } from '../../shared/bundled-ripgrep'
|
||||
|
||||
import {
|
||||
bundledRipgrepCommand,
|
||||
bundledRipgrepContentKey,
|
||||
bundledRipgrepWslSpawnOptions,
|
||||
resetBundledRipgrepPathCacheForTests,
|
||||
resolveBundledRipgrepPath
|
||||
@@ -32,21 +23,6 @@ describe('bundled ripgrep path', () => {
|
||||
resetBundledRipgrepPathCacheForTests()
|
||||
})
|
||||
|
||||
it('resolves the checkout binary for this host in development', () => {
|
||||
setResourcesPath(undefined)
|
||||
const command = bundledRipgrepCommand()
|
||||
|
||||
expect(command).toContain(join('@vscode', 'ripgrep-universal', 'bin'))
|
||||
expect(existsSync(command)).toBe(true)
|
||||
})
|
||||
|
||||
it('resolves the Linux build for WSL-routed spawns', () => {
|
||||
setResourcesPath(undefined)
|
||||
const linuxPlatform = toBundledRipgrepPlatform('linux', process.arch)
|
||||
|
||||
expect(bundledRipgrepCommand({ wsl: true })).toContain(join('bin', `${linuxPlatform}`, 'rg'))
|
||||
})
|
||||
|
||||
it('prefers the packaged resources copy', () => {
|
||||
const resourcesDir = mkdtempSync(join(tmpdir(), 'orca-rg-resources-'))
|
||||
try {
|
||||
@@ -62,34 +38,6 @@ describe('bundled ripgrep path', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('names no bundled build for platforms outside the relay set', () => {
|
||||
expect(toBundledRipgrepPlatform('freebsd', 'x64')).toBeNull()
|
||||
expect(toBundledRipgrepPlatform('win32', 'ia32')).toBeNull()
|
||||
})
|
||||
|
||||
it('keys the remote cache on the shipped bytes', () => {
|
||||
setResourcesPath(undefined)
|
||||
const platform = toBundledRipgrepPlatform(process.platform, process.arch)!
|
||||
const key = bundledRipgrepContentKey(platform)
|
||||
|
||||
expect(key).toMatch(/^[0-9a-f]{16}$/)
|
||||
const otherPlatform = platform === 'win32-x64' ? 'linux-x64' : 'win32-x64'
|
||||
expect(bundledRipgrepContentKey(otherPlatform)).not.toBe(key)
|
||||
})
|
||||
|
||||
it('picks the distro-arch Linux build and fails closed when its drive is unavailable', () => {
|
||||
const { wslShellCommand } = bundledRipgrepWslSpawnOptions(
|
||||
'C:\\Program Files\\Orca\\resources\\ripgrep\\linux-x64\\rg'
|
||||
)
|
||||
|
||||
expect(wslShellCommand).toContain(`wslpath -u 'C:\\Program Files\\Orca\\resources\\ripgrep'`)
|
||||
expect(wslShellCommand).toContain('aarch64|arm64) a=linux-arm64')
|
||||
expect(wslShellCommand).toContain('printf %s "$d/$a/rg"')
|
||||
expect(wslShellCommand).toContain('else printf /dev/null/orca-ripgrep-unavailable')
|
||||
expect(wslShellCommand).not.toContain('else printf rg')
|
||||
expect(bundledRipgrepWslSpawnOptions('rg')).toEqual({})
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'never executes a PATH ripgrep when WSL cannot translate the install drive',
|
||||
async () => {
|
||||
|
||||
@@ -101,13 +101,6 @@ describe('device registry auth checks see edits made on disk', () => {
|
||||
expect(registry.validateToken(added.token)?.deviceId).toBe(added.deviceId)
|
||||
})
|
||||
|
||||
it('stays usable when there is no file at all', () => {
|
||||
const registry = new DeviceRegistry(dir)
|
||||
|
||||
expect(registry.validateToken('not-a-token')).toBeNull()
|
||||
expect(registry.lookupDeviceKey('missing-device')).toEqual({ kind: 'unknown' })
|
||||
})
|
||||
|
||||
it('keeps what it has when the file turns corrupt, since that proves no removal', () => {
|
||||
const registry = new DeviceRegistry(dir)
|
||||
const desktop = registry.addDevice('desktop', 'runtime')
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createMobileSessionTabsNotifyCoalescer } from './mobile-session-tabs-notify-coalescer'
|
||||
|
||||
describe('createMobileSessionTabsNotifyCoalescer', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('coalesces a rapid burst of title/status flips into one trailing emit (repro)', () => {
|
||||
// Title spinners generate bursts; publish only the latest state after the trailing window.
|
||||
const emit = vi.fn()
|
||||
const coalescer = createMobileSessionTabsNotifyCoalescer(emit)
|
||||
|
||||
const FLIPS = 20
|
||||
for (let i = 0; i < FLIPS; i++) {
|
||||
coalescer.schedule('worktree-1')
|
||||
vi.advanceTimersByTime(10)
|
||||
}
|
||||
expect(emit).not.toHaveBeenCalled()
|
||||
|
||||
vi.advanceTimersByTime(50)
|
||||
|
||||
expect(emit).toHaveBeenCalledTimes(1)
|
||||
expect(emit).toHaveBeenCalledWith('worktree-1')
|
||||
})
|
||||
|
||||
it('force-flushes under sustained churn so the emit is never starved', () => {
|
||||
const emit = vi.fn()
|
||||
const coalescer = createMobileSessionTabsNotifyCoalescer(emit)
|
||||
|
||||
// Sustained churn must still publish within the 250ms cap.
|
||||
for (let i = 0; i < 100; i++) {
|
||||
coalescer.schedule('worktree-1')
|
||||
vi.advanceTimersByTime(30)
|
||||
}
|
||||
|
||||
expect(emit).toHaveBeenCalled()
|
||||
expect(emit).toHaveBeenCalledWith('worktree-1')
|
||||
})
|
||||
|
||||
it('keeps per-worktree windows independent', () => {
|
||||
const emit = vi.fn()
|
||||
const coalescer = createMobileSessionTabsNotifyCoalescer(emit)
|
||||
|
||||
coalescer.schedule('worktree-1')
|
||||
coalescer.schedule('worktree-2')
|
||||
vi.advanceTimersByTime(50)
|
||||
|
||||
expect(emit).toHaveBeenCalledTimes(2)
|
||||
expect(emit).toHaveBeenCalledWith('worktree-1')
|
||||
expect(emit).toHaveBeenCalledWith('worktree-2')
|
||||
})
|
||||
|
||||
it('cancel() drops a pending notify so a structural emit can supersede it', () => {
|
||||
const emit = vi.fn()
|
||||
const coalescer = createMobileSessionTabsNotifyCoalescer(emit)
|
||||
|
||||
coalescer.schedule('worktree-1')
|
||||
// Structural changes emit immediately elsewhere and cancel trailing notifications.
|
||||
coalescer.cancel('worktree-1')
|
||||
vi.advanceTimersByTime(50)
|
||||
|
||||
expect(emit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('flush() emits the pending notify immediately', () => {
|
||||
const emit = vi.fn()
|
||||
const coalescer = createMobileSessionTabsNotifyCoalescer(emit)
|
||||
|
||||
coalescer.schedule('worktree-1')
|
||||
coalescer.flush('worktree-1')
|
||||
|
||||
expect(emit).toHaveBeenCalledTimes(1)
|
||||
vi.advanceTimersByTime(50)
|
||||
expect(emit).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('flush() is a no-op when nothing is pending', () => {
|
||||
const emit = vi.fn()
|
||||
const coalescer = createMobileSessionTabsNotifyCoalescer(emit)
|
||||
|
||||
coalescer.flush('worktree-1')
|
||||
|
||||
expect(emit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('flushAll() drains every pending worktree (subscription close)', () => {
|
||||
const emit = vi.fn()
|
||||
const coalescer = createMobileSessionTabsNotifyCoalescer(emit)
|
||||
|
||||
coalescer.schedule('worktree-1')
|
||||
coalescer.schedule('worktree-2')
|
||||
coalescer.flushAll()
|
||||
|
||||
expect(emit).toHaveBeenCalledTimes(2)
|
||||
vi.advanceTimersByTime(50)
|
||||
expect(emit).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('dispose() drops pending timers without emitting', () => {
|
||||
const emit = vi.fn()
|
||||
const coalescer = createMobileSessionTabsNotifyCoalescer(emit)
|
||||
|
||||
coalescer.schedule('worktree-1')
|
||||
coalescer.dispose()
|
||||
vi.advanceTimersByTime(50)
|
||||
|
||||
expect(emit).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import type Database from '../../sqlite/sync-database'
|
||||
import { OrchestrationDb, type MessageType } from './db'
|
||||
|
||||
import { OrchestrationDb } from './db'
|
||||
|
||||
const runId = 'run_legacy_local'
|
||||
|
||||
@@ -17,26 +17,6 @@ describe('OrchestrationDb', () => {
|
||||
}
|
||||
|
||||
describe('messages', () => {
|
||||
it('inserts and retrieves a message', () => {
|
||||
const d = createDb()
|
||||
const msg = d.insertMessage({
|
||||
runId,
|
||||
from: 'term_a',
|
||||
to: 'term_b',
|
||||
subject: 'hello',
|
||||
body: 'world'
|
||||
})
|
||||
expect(msg.id).toMatch(/^msg_/)
|
||||
expect(msg.from_handle).toBe('term_a')
|
||||
expect(msg.to_handle).toBe('term_b')
|
||||
expect(msg.subject).toBe('hello')
|
||||
expect(msg.body).toBe('world')
|
||||
expect(msg.type).toBe('status')
|
||||
expect(msg.priority).toBe('normal')
|
||||
expect(msg.read).toBe(0)
|
||||
expect(msg.sequence).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('returns unread messages in sequence order', () => {
|
||||
const d = createDb()
|
||||
d.insertMessage({ runId, from: 'a', to: 'b', subject: 'first' })
|
||||
@@ -49,28 +29,6 @@ describe('OrchestrationDb', () => {
|
||||
expect(unread[1].subject).toBe('second')
|
||||
})
|
||||
|
||||
it('filters unread by type', () => {
|
||||
const d = createDb()
|
||||
d.insertMessage({
|
||||
runId,
|
||||
from: 'a',
|
||||
to: 'b',
|
||||
subject: 'status msg',
|
||||
type: 'status'
|
||||
})
|
||||
d.insertMessage({
|
||||
runId,
|
||||
from: 'a',
|
||||
to: 'b',
|
||||
subject: 'done msg',
|
||||
type: 'worker_done'
|
||||
})
|
||||
|
||||
const filtered = d.getUnreadMessages('b', ['worker_done'])
|
||||
expect(filtered).toHaveLength(1)
|
||||
expect(filtered[0].type).toBe('worker_done')
|
||||
})
|
||||
|
||||
it('excludes already-delivered rows from getUndeliveredUnreadMessages', () => {
|
||||
const d = createDb()
|
||||
const m1 = d.insertMessage({ runId, from: 'a', to: 'b', subject: 'one' })
|
||||
@@ -86,19 +44,6 @@ describe('OrchestrationDb', () => {
|
||||
expect(unread).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('creates the undelivered inbox index used by push delivery', () => {
|
||||
const d = createDb()
|
||||
const sqlite = (d as unknown as { db: Database.Database }).db
|
||||
|
||||
const indexes = sqlite
|
||||
.prepare(
|
||||
`SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'messages' AND name = 'idx_messages_undelivered_inbox'`
|
||||
)
|
||||
.all()
|
||||
|
||||
expect(indexes).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('filters getUndeliveredUnreadMessages by type', () => {
|
||||
const d = createDb()
|
||||
d.insertMessage({
|
||||
@@ -132,28 +77,5 @@ describe('OrchestrationDb', () => {
|
||||
expect(unread).toHaveLength(1)
|
||||
expect(unread[0].id).toBe(m2.id)
|
||||
})
|
||||
|
||||
it('rejects invalid message type', () => {
|
||||
const d = createDb()
|
||||
expect(() =>
|
||||
d.insertMessage({
|
||||
runId,
|
||||
from: 'a',
|
||||
to: 'b',
|
||||
subject: 'bad',
|
||||
type: 'invalid' as MessageType
|
||||
})
|
||||
).toThrow()
|
||||
})
|
||||
|
||||
it('getInbox returns all messages across recipients', () => {
|
||||
const d = createDb()
|
||||
d.insertMessage({ runId, from: 'a', to: 'b', subject: 'one' })
|
||||
d.insertMessage({ runId, from: 'a', to: 'c', subject: 'two' })
|
||||
d.insertMessage({ runId, from: 'b', to: 'a', subject: 'three' })
|
||||
|
||||
const inbox = d.getInbox(10)
|
||||
expect(inbox).toHaveLength(3)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -55,35 +55,6 @@ describe('mutation receipt capacity schema', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('uses the completed receipt index for age and capacity pruning', () => {
|
||||
db = new OrchestrationDb(':memory:')
|
||||
const sqlite = sqliteFor(db)
|
||||
insertReceipts(sqlite, 10, 'completed')
|
||||
|
||||
const agePlan = sqlite
|
||||
.prepare(
|
||||
`EXPLAIN QUERY PLAN
|
||||
DELETE FROM mutation_receipts
|
||||
WHERE state = 'completed'
|
||||
AND updated_at < datetime('now', ?)`
|
||||
)
|
||||
.all('-30 days') as { detail: string }[]
|
||||
const capacityPlan = sqlite
|
||||
.prepare(
|
||||
`EXPLAIN QUERY PLAN
|
||||
SELECT rowid FROM mutation_receipts
|
||||
WHERE state = 'completed'
|
||||
ORDER BY updated_at ASC, rowid ASC
|
||||
LIMIT ?`
|
||||
)
|
||||
.all(64) as { detail: string }[]
|
||||
const details = [...agePlan, ...capacityPlan].map((row) => row.detail).join('\n')
|
||||
|
||||
expect(details).toContain('idx_mutation_receipts_completed_updated')
|
||||
expect(details).not.toContain('USE TEMP B-TREE')
|
||||
expect(details).not.toMatch(/SCAN mutation_receipts(?:\n|$)/)
|
||||
})
|
||||
|
||||
it('migrates a populated v25 database and tracks writes from older connections', () => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), 'orca-mutation-receipt-migration-'))
|
||||
const dbPath = join(tempDir, 'orchestration.db')
|
||||
|
||||
@@ -47,14 +47,6 @@ describe('buildStructuredJournalArchive', () => {
|
||||
expect(built.messages[0]?.id).not.toBe('item-0')
|
||||
})
|
||||
|
||||
it('reports the end it actually dropped', () => {
|
||||
const built = archive(longJournal(200))
|
||||
expect(built.warnings).toContain(
|
||||
'The oldest archived journal messages were dropped to fit the size bound.'
|
||||
)
|
||||
expect(built.warnings).not.toContain('Transcript response was clipped to the wire-size limit.')
|
||||
})
|
||||
|
||||
it('stays inside the durable bound', () => {
|
||||
const built = archive(longJournal(200))
|
||||
expect(Buffer.byteLength(JSON.stringify(built.messages), 'utf8')).toBeLessThanOrEqual(
|
||||
@@ -62,15 +54,6 @@ describe('buildStructuredJournalArchive', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps a short journal whole and unflagged', () => {
|
||||
const built = archive(longJournal(3))
|
||||
expect(built.limited).toBe(false)
|
||||
expect(built.messages.map((message) => message.id)).toEqual(['item-0', 'item-1', 'item-2'])
|
||||
expect(built.warnings).not.toContain(
|
||||
'The oldest archived journal messages were dropped to fit the size bound.'
|
||||
)
|
||||
})
|
||||
|
||||
it('archives raw result-before-call order without publishing client presentation markers', () => {
|
||||
const items: AgentJournalRenderItem[] = [
|
||||
{
|
||||
@@ -124,10 +107,4 @@ describe('buildStructuredJournalArchive', () => {
|
||||
expect(projected[1]).toMatchObject({ id: 'old-x', role: 'tool', blocks: [{ output: 'OLD X' }] })
|
||||
expect(foldToolMessages(projected)).toEqual(projected)
|
||||
})
|
||||
|
||||
it('still reports omitted older items when the page itself was bounded', () => {
|
||||
const built = archive(longJournal(2), true)
|
||||
expect(built.limited).toBe(true)
|
||||
expect(built.warnings).toContain('Older journal items were omitted from the bounded archive.')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,19 +2,6 @@ import { describe, expect, it, vi } from 'vitest'
|
||||
import { PtyShellOwnershipMirror } from './pty-shell-ownership-mirror'
|
||||
|
||||
describe('PtyShellOwnershipMirror', () => {
|
||||
it('arms the recovery trigger from a seeded alternate-screen state', async () => {
|
||||
const confirm = vi.fn(async () => true)
|
||||
const mirror = new PtyShellOwnershipMirror(confirm)
|
||||
|
||||
// Restored bytes bypass scan; seed alternate-screen state so later TUI death can prove shell ownership.
|
||||
mirror.seedOwner(undefined, { alternateScreen: true })
|
||||
mirror.scan('\x1b]133;D;137\x07')
|
||||
|
||||
await vi.waitFor(() => expect(confirm).toHaveBeenCalledTimes(1))
|
||||
await mirror.settle()
|
||||
expect(mirror.owner).toBe('shell')
|
||||
})
|
||||
|
||||
it('asks at the real D after refuted stray Ds, in lockstep with the host barrier', async () => {
|
||||
let hostGrounded = false
|
||||
const confirm = vi.fn(async () => hostGrounded)
|
||||
@@ -53,17 +40,6 @@ describe('PtyShellOwnershipMirror', () => {
|
||||
expect(mirror.owner).toBeUndefined()
|
||||
})
|
||||
|
||||
it('bounds settle() when a proof hangs', async () => {
|
||||
const mirror = new PtyShellOwnershipMirror(() => new Promise(() => {}))
|
||||
mirror.seedOwner(undefined, { alternateScreen: true })
|
||||
mirror.scan('\x1b]133;D;137\x07')
|
||||
|
||||
const start = Date.now()
|
||||
await mirror.settle()
|
||||
expect(Date.now() - start).toBeLessThan(2000)
|
||||
expect(mirror.owner).toBeUndefined()
|
||||
})
|
||||
|
||||
it('retires a hung confirmation so a later candidate can still prove ownership', async () => {
|
||||
let calls = 0
|
||||
const mirror = new PtyShellOwnershipMirror(() => {
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
/** Forward sessionOptions to both terminal paths so the user's model/effort/mode override configured args as on structured chat. */
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { RpcContext } from '../core'
|
||||
import {
|
||||
CAPABLE_CLIENT,
|
||||
STRUCTURED_PREFERENCE,
|
||||
methodNamed,
|
||||
rpcContext,
|
||||
runtimeStub,
|
||||
type AgentLaunchRuntimeStub as RuntimeStub
|
||||
} from './agent-launch.test-fixture'
|
||||
|
||||
vi.mock('./structured-agent-session-create', () => ({
|
||||
createStructuredAgentSessionForWorktree: async () => ({
|
||||
ok: true,
|
||||
value: { sessionId: 'sess-1' }
|
||||
})
|
||||
}))
|
||||
|
||||
const { AGENT_LAUNCH_METHODS } = await import('./agent-launch')
|
||||
const AGENT_LAUNCH = methodNamed(AGENT_LAUNCH_METHODS, 'agent.launch')
|
||||
|
||||
const TERMINAL_ONLY = {}
|
||||
const EXISTING_LAUNCH = { agent: 'claude', target: { kind: 'existing', worktree: 'id:wt-7' } }
|
||||
const CREATE_LAUNCH = {
|
||||
agent: 'claude',
|
||||
target: { kind: 'create-worktree', create: { repo: 'id:repo-1', name: 'task' } }
|
||||
}
|
||||
const PICKS = { model: 'opus', effort: 'high' }
|
||||
|
||||
async function launch(params: unknown, runtime: RuntimeStub, context: Partial<RpcContext> = {}) {
|
||||
const parsed = AGENT_LAUNCH.params.safeParse(params)
|
||||
if (!parsed.success) {
|
||||
throw new Error(parsed.error.issues[0]?.message ?? 'invalid')
|
||||
}
|
||||
return AGENT_LAUNCH.handler(parsed.data, rpcContext(runtime, { ...CAPABLE_CLIENT, ...context }))
|
||||
}
|
||||
|
||||
function terminalOptions(runtime: RuntimeStub): Record<string, unknown> {
|
||||
return runtime.createTerminal.mock.calls[0]?.[1] ?? {}
|
||||
}
|
||||
|
||||
function createArgs(runtime: RuntimeStub): Record<string, unknown> {
|
||||
return runtime.createManagedWorktree.mock.calls[0]?.[0] ?? {}
|
||||
}
|
||||
|
||||
describe('a terminal launch into an existing workspace', () => {
|
||||
it('starts the agent with the picks the launch carried', async () => {
|
||||
const runtime = runtimeStub({ settings: TERMINAL_ONLY })
|
||||
|
||||
await launch({ ...EXISTING_LAUNCH, sessionOptions: PICKS }, runtime)
|
||||
|
||||
expect(terminalOptions(runtime)).toMatchObject({ launchPreferences: PICKS })
|
||||
})
|
||||
|
||||
it('adds no preferences when the launch carried none', async () => {
|
||||
const runtime = runtimeStub({ settings: TERMINAL_ONLY })
|
||||
|
||||
await launch(EXISTING_LAUNCH, runtime)
|
||||
|
||||
expect(terminalOptions(runtime)).not.toHaveProperty('launchPreferences')
|
||||
})
|
||||
|
||||
it('keeps the picks through a downgrade from structured to terminal', async () => {
|
||||
const runtime = runtimeStub({
|
||||
settings: STRUCTURED_PREFERENCE,
|
||||
createSupport: { supported: false, reason: 'wsl' }
|
||||
})
|
||||
|
||||
await launch({ ...EXISTING_LAUNCH, sessionOptions: PICKS }, runtime)
|
||||
|
||||
expect(terminalOptions(runtime)).toMatchObject({ launchPreferences: PICKS })
|
||||
})
|
||||
|
||||
it('drops options that are not launch preferences', async () => {
|
||||
const runtime = runtimeStub({ settings: TERMINAL_ONLY })
|
||||
|
||||
await launch({ ...EXISTING_LAUNCH, sessionOptions: { permissionMode: 'plan' } }, runtime)
|
||||
|
||||
expect(terminalOptions(runtime)).not.toHaveProperty('launchPreferences')
|
||||
})
|
||||
})
|
||||
|
||||
describe('a terminal launch that creates its workspace', () => {
|
||||
it('starts the startup agent with the picks the launch carried', async () => {
|
||||
const runtime = runtimeStub({ settings: TERMINAL_ONLY })
|
||||
|
||||
await launch({ ...CREATE_LAUNCH, sessionOptions: PICKS }, runtime)
|
||||
|
||||
expect(createArgs(runtime)).toMatchObject({ startupLaunchPreferences: PICKS })
|
||||
})
|
||||
|
||||
it('sends no startup preferences when the launch carried none', async () => {
|
||||
const runtime = runtimeStub({ settings: TERMINAL_ONLY })
|
||||
|
||||
await launch(CREATE_LAUNCH, runtime)
|
||||
|
||||
expect(createArgs(runtime)).not.toHaveProperty('startupLaunchPreferences')
|
||||
})
|
||||
|
||||
it('sends no startup preferences when the workspace gets a chat instead', async () => {
|
||||
// The chat reads the same picks from its own create; a startup terminal is not created at all.
|
||||
const runtime = runtimeStub({ settings: STRUCTURED_PREFERENCE })
|
||||
|
||||
await launch({ ...CREATE_LAUNCH, sessionOptions: PICKS }, runtime)
|
||||
|
||||
expect(createArgs(runtime)).not.toHaveProperty('startupLaunchPreferences')
|
||||
})
|
||||
})
|
||||
@@ -7,15 +7,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
MOBILE_WEB_BUNDLE_CHUNK_BYTES as RANGE_BYTES,
|
||||
MOBILE_WEB_BUNDLE_RANGE_METHOD,
|
||||
MobileWebBundleManifestResultSchema,
|
||||
MobileWebBundleRangeResultSchema,
|
||||
type MobileWebBundleRangeResult
|
||||
} from '../../../../shared/mobile-web-bundle/bundle-rpc-contract'
|
||||
|
||||
import { resetBundledMobileWebBundleCacheForTests } from '../../bundled-mobile-web-bundle'
|
||||
import { MOBILE_RPC_METHOD_ALLOWLIST } from '../../runtime-rpc/runtime-rpc-mobile-method-allowlist'
|
||||
|
||||
import type { RpcResponse } from '../core'
|
||||
import type { RpcDispatcher } from '../dispatcher'
|
||||
import { ALL_RPC_METHODS } from './index'
|
||||
|
||||
import { resetMobileWebBundleAssetVerdictsForTests } from './mobile-web-bundle-asset-reader'
|
||||
import { resetMobileWebBundleReadAdmissionForTests } from './mobile-web-bundle-read-admission'
|
||||
import {
|
||||
@@ -86,22 +86,6 @@ describe('mobileWeb.bundle.range on an install that carries a bundle', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('names the range grid on the manifest reply', async () => {
|
||||
const response = await call('mobileWeb.bundle.manifest')
|
||||
const result = MobileWebBundleManifestResultSchema.parse(response.ok && response.result)
|
||||
expect(result.rangeBytes).toBe(RANGE_BYTES)
|
||||
})
|
||||
|
||||
// Manifest discovery must name a method the mobile allowlist actually permits.
|
||||
it('names the grid only for a method a paired phone can actually call', async () => {
|
||||
const response = await call('mobileWeb.bundle.manifest')
|
||||
expect(
|
||||
MobileWebBundleManifestResultSchema.parse(response.ok && response.result).rangeBytes
|
||||
).toBeDefined()
|
||||
expect(ALL_RPC_METHODS.map((method) => method.name)).toContain(MOBILE_WEB_BUNDLE_RANGE_METHOD)
|
||||
expect(MOBILE_RPC_METHOD_ALLOWLIST.has(MOBILE_WEB_BUNDLE_RANGE_METHOD)).toBe(true)
|
||||
})
|
||||
|
||||
it('pages every asset back byte for byte on the range grid, each reply a strict result', async () => {
|
||||
for (const asset of bundle.assets) {
|
||||
const pieces: Buffer[] = []
|
||||
@@ -155,23 +139,4 @@ describe('mobileWeb.bundle.range on an install that carries a bundle', () => {
|
||||
Buffer.from(result.dataBase64, 'base64').equals(INCOMPRESSIBLE.bytes.subarray(0, RANGE_BYTES))
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('serves a zero-byte asset as one empty identity range at eof', async () => {
|
||||
const mark = bundle.assets.find((asset) => asset.byteLength === 0)!
|
||||
|
||||
const result = body(await range({ buildId: bundle.buildId, path: mark.path, offset: 0 }))
|
||||
|
||||
expect(result).toMatchObject({ encoding: 'identity', dataBase64: '', eof: true })
|
||||
})
|
||||
|
||||
it('refuses a caller-chosen length at the params schema', async () => {
|
||||
const response = await range({
|
||||
buildId: bundle.buildId,
|
||||
path: COMPRESSIBLE.path,
|
||||
offset: 0,
|
||||
length: 1000
|
||||
})
|
||||
|
||||
expect(response.ok ? undefined : response.error.code).toBe('invalid_argument')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,7 +5,6 @@ import type { OrchestrationDb } from '../../../../orchestration/db'
|
||||
|
||||
describe('orchestration RPC methods', () => {
|
||||
const h = createOrchestrationRpcHarness()
|
||||
const { findMethod } = h
|
||||
let db: OrchestrationDb
|
||||
let ctx: RpcContext
|
||||
|
||||
@@ -67,30 +66,6 @@ describe('orchestration RPC methods', () => {
|
||||
expect(db.getTask(foreignTask.id)?.status).toBe('ready')
|
||||
expect(db.listGates({ taskId: foreignTask.id })).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('rejects invalid options JSON', async () => {
|
||||
setup()
|
||||
const task = db.createTask({ spec: 'work' })
|
||||
await expect(
|
||||
call('orchestration.gateCreate', {
|
||||
task: task.id,
|
||||
question: 'ok?',
|
||||
options: 'not-json'
|
||||
})
|
||||
).rejects.toThrow('Invalid --options')
|
||||
})
|
||||
|
||||
it('rejects options that are not string arrays', async () => {
|
||||
setup()
|
||||
const task = db.createTask({ spec: 'work' })
|
||||
await expect(
|
||||
call('orchestration.gateCreate', {
|
||||
task: task.id,
|
||||
question: 'ok?',
|
||||
options: JSON.stringify(['yes', 1])
|
||||
})
|
||||
).rejects.toThrow('Invalid --options')
|
||||
})
|
||||
})
|
||||
|
||||
describe('orchestration.gateResolve', () => {
|
||||
@@ -110,42 +85,5 @@ describe('orchestration RPC methods', () => {
|
||||
const updated = db.getTask(task.id)
|
||||
expect(updated?.status).toBe('ready')
|
||||
})
|
||||
|
||||
it('throws on nonexistent gate', async () => {
|
||||
setup()
|
||||
await expect(
|
||||
call('orchestration.gateResolve', { id: 'gate_fake', resolution: 'yes' })
|
||||
).rejects.toThrow('Gate not found')
|
||||
})
|
||||
})
|
||||
|
||||
describe('orchestration.gateList', () => {
|
||||
it('lists all gates', async () => {
|
||||
setup()
|
||||
const t1 = db.createTask({ spec: 'a' })
|
||||
const t2 = db.createTask({ spec: 'b' })
|
||||
db.createGate({ taskId: t1.id, question: 'q1' })
|
||||
db.createGate({ taskId: t2.id, question: 'q2' })
|
||||
|
||||
const result = (await call('orchestration.gateList', {})) as { count: number }
|
||||
expect(result.count).toBe(2)
|
||||
})
|
||||
|
||||
it('filters by status', async () => {
|
||||
setup()
|
||||
const task = db.createTask({ spec: 'work' })
|
||||
const gate = db.createGate({ taskId: task.id, question: 'q' })
|
||||
db.resolveGate(gate.id, 'yes')
|
||||
|
||||
const result = (await call('orchestration.gateList', {
|
||||
status: 'resolved'
|
||||
})) as { count: number }
|
||||
expect(result.count).toBe(1)
|
||||
})
|
||||
|
||||
it('rejects invalid status filters', () => {
|
||||
const method = findMethod('orchestration.gateList')
|
||||
expect(() => method.params!.parse({ status: 'closed' })).toThrow()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
-120
@@ -1,120 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { RuntimeTerminalPromptDelivery } from '../../../../../../shared/runtime-terminal-contracts'
|
||||
import type { OrcaRuntimeService } from '../../../../orca-runtime'
|
||||
import { observeWorkerTurnStart } from './worker-start-turn-observation'
|
||||
|
||||
function delivery(
|
||||
overrides: Partial<RuntimeTerminalPromptDelivery> = {}
|
||||
): RuntimeTerminalPromptDelivery {
|
||||
return {
|
||||
requestId: 'req-1',
|
||||
stages: ['input_accepted'],
|
||||
provider: 'codex',
|
||||
observation: 'supported',
|
||||
processIncarnation: 'inc-1',
|
||||
generation: 1,
|
||||
baselineWorkingSequence: 0,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function runtimeObserving(result: RuntimeTerminalPromptDelivery): {
|
||||
runtime: OrcaRuntimeService
|
||||
observe: ReturnType<typeof vi.fn>
|
||||
} {
|
||||
const observe = vi.fn().mockResolvedValue(result)
|
||||
return {
|
||||
runtime: { observeTerminalAgentPrompt: observe } as unknown as OrcaRuntimeService,
|
||||
observe
|
||||
}
|
||||
}
|
||||
|
||||
describe('observeWorkerTurnStart', () => {
|
||||
it('treats a missing receipt as unsupported observation, never as failure', async () => {
|
||||
const { runtime, observe } = runtimeObserving(delivery())
|
||||
await expect(
|
||||
observeWorkerTurnStart({ runtime, terminalHandle: 'term_w', prompt: undefined })
|
||||
).resolves.toEqual({ verdict: 'unsupported' })
|
||||
expect(observe).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('accepts a first-stage turn_started without a second observation pass', async () => {
|
||||
const prompt = delivery({ stages: ['input_accepted', 'turn_started'] })
|
||||
const { runtime, observe } = runtimeObserving(prompt)
|
||||
await expect(
|
||||
observeWorkerTurnStart({ runtime, terminalHandle: 'term_w', prompt })
|
||||
).resolves.toEqual({ verdict: 'observed', prompt })
|
||||
expect(observe).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports observed when the second-stage observer sees the turn start', async () => {
|
||||
const observed = delivery({ stages: ['input_accepted', 'turn_started'] })
|
||||
const { runtime, observe } = runtimeObserving(observed)
|
||||
await expect(
|
||||
observeWorkerTurnStart({
|
||||
runtime,
|
||||
terminalHandle: 'term_w',
|
||||
prompt: delivery(),
|
||||
timeoutMs: 5
|
||||
})
|
||||
).resolves.toEqual({ verdict: 'observed', prompt: observed })
|
||||
expect(observe).toHaveBeenCalledWith('term_w', delivery(), 5)
|
||||
})
|
||||
|
||||
it('reports unobserved — not dead — when a supported observation stalls', async () => {
|
||||
const { runtime } = runtimeObserving(delivery())
|
||||
await expect(
|
||||
observeWorkerTurnStart({
|
||||
runtime,
|
||||
terminalHandle: 'term_w',
|
||||
prompt: delivery(),
|
||||
timeoutMs: 5
|
||||
})
|
||||
).resolves.toMatchObject({ verdict: 'unobserved' })
|
||||
})
|
||||
|
||||
it('reports permission as positive liveness', async () => {
|
||||
const observed = delivery({ observation: 'permission' })
|
||||
const { runtime } = runtimeObserving(observed)
|
||||
await expect(
|
||||
observeWorkerTurnStart({
|
||||
runtime,
|
||||
terminalHandle: 'term_w',
|
||||
prompt: delivery(),
|
||||
timeoutMs: 5
|
||||
})
|
||||
).resolves.toEqual({ verdict: 'permission', prompt: observed })
|
||||
})
|
||||
|
||||
it('treats a replaced incarnation as unobserved rather than unsupported', async () => {
|
||||
const observed = delivery({ observation: 'incarnation_replaced' })
|
||||
const { runtime } = runtimeObserving(observed)
|
||||
await expect(
|
||||
observeWorkerTurnStart({
|
||||
runtime,
|
||||
terminalHandle: 'term_w',
|
||||
prompt: delivery(),
|
||||
timeoutMs: 5
|
||||
})
|
||||
).resolves.toEqual({ verdict: 'unobserved', prompt: observed })
|
||||
})
|
||||
|
||||
it('leaves an unsupported provider on the accepted receipt', async () => {
|
||||
const prompt = delivery({ provider: 'unsupported', observation: 'unsupported' })
|
||||
const { runtime, observe } = runtimeObserving(prompt)
|
||||
await expect(
|
||||
observeWorkerTurnStart({ runtime, terminalHandle: 'term_w', prompt })
|
||||
).resolves.toEqual({ verdict: 'unsupported', prompt })
|
||||
expect(observe).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('preserves uncertainty when observation loses the terminal binding', async () => {
|
||||
const prompt = delivery()
|
||||
const { runtime, observe } = runtimeObserving(prompt)
|
||||
observe.mockRejectedValue(new Error('terminal_handle_stale'))
|
||||
await expect(
|
||||
observeWorkerTurnStart({ runtime, terminalHandle: 'term_w', prompt })
|
||||
).resolves.toEqual({ verdict: 'unobserved', prompt })
|
||||
expect(observe).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
-35
@@ -124,26 +124,6 @@ describe('worker-stop against a terminal we lost contact with', () => {
|
||||
expect(stopped.lastError).toContain('could not be confirmed stopped')
|
||||
})
|
||||
|
||||
it('uses the canonical live verdict for an observed process', async () => {
|
||||
vi.spyOn(runtime, 'showTerminal').mockResolvedValue({
|
||||
handle: 'term_worker',
|
||||
worktreeId: 'repo::worktree',
|
||||
connected: true,
|
||||
status: 'running'
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'getTerminalLivenessVerdict').mockReturnValue({
|
||||
status: 'live',
|
||||
ptyIds: ['runtime:pty:1']
|
||||
})
|
||||
const dispatch = createWorker()
|
||||
|
||||
await expect(
|
||||
call('orchestration.workerShow', { dispatch: dispatch.id })
|
||||
).resolves.toMatchObject({
|
||||
observation: { status: 'live', exactWorker: true }
|
||||
})
|
||||
})
|
||||
|
||||
it('does not close a legacy worker terminal without an ownership record', async () => {
|
||||
vi.spyOn(runtime, 'showTerminal').mockResolvedValue({
|
||||
handle: 'term_worker',
|
||||
@@ -184,19 +164,4 @@ describe('worker-stop against a terminal we lost contact with', () => {
|
||||
)
|
||||
expect(db.getWorkerDispatch(dispatch.id)?.state).toBe('stopping')
|
||||
})
|
||||
|
||||
it('still reports a locally observed exit as exited', async () => {
|
||||
const dispatch = createWorker()
|
||||
|
||||
await expect(
|
||||
call('orchestration.workerShow', { dispatch: dispatch.id })
|
||||
).resolves.toMatchObject({
|
||||
observation: { status: 'exited', exactWorker: true }
|
||||
})
|
||||
|
||||
const stopped = (await call('orchestration.workerStop', { dispatch: dispatch.id })) as {
|
||||
lastError: string
|
||||
}
|
||||
expect(stopped.lastError).toBe('The recorded worker process is exited; no terminal was closed.')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -6,11 +6,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import type { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import type { RpcResponse } from '../core'
|
||||
import { RpcDispatcher } from '../dispatcher'
|
||||
import {
|
||||
AGENT_SESSION_ATTACHMENTS_RUNTIME_CAPABILITY,
|
||||
AGENT_SESSION_PHONE_ATTACHMENTS_RUNTIME_CAPABILITY,
|
||||
RUNTIME_CAPABILITIES
|
||||
} from '../../../../shared/protocol-version'
|
||||
|
||||
import { AgentSessionAttachmentStore } from '../../../native-chat/agent-session-attachments/agent-session-attachment-store'
|
||||
import { setAgentSessionAttachmentStore } from '../../../native-chat/agent-session-attachments/agent-session-attachment-store-registry'
|
||||
import { STRUCTURED_AGENT_SESSION_ATTACHMENT_METHODS } from './structured-agent-session-attachments'
|
||||
@@ -103,11 +99,6 @@ async function uploadBytes(name: string, bytes: Buffer): Promise<string> {
|
||||
}
|
||||
|
||||
describe('agentSessionAttachment.*', () => {
|
||||
it('is advertised, so a client can tell a host with the store from an older one', () => {
|
||||
expect(RUNTIME_CAPABILITIES).toContain(AGENT_SESSION_ATTACHMENTS_RUNTIME_CAPABILITY)
|
||||
expect(RUNTIME_CAPABILITIES).toContain(AGENT_SESSION_PHONE_ATTACHMENTS_RUNTIME_CAPABILITY)
|
||||
})
|
||||
|
||||
it('stores an upload for the chat and hands back the server path', async () => {
|
||||
const { uploadId } = result<{ uploadId: string }>(
|
||||
await call(
|
||||
@@ -134,27 +125,6 @@ describe('agentSessionAttachment.*', () => {
|
||||
expect(preview).toMatchObject({ ok: true, result: { isBinary: true, mimeType: 'image/png' } })
|
||||
})
|
||||
|
||||
it('refuses a client that cannot read structured sessions', async () => {
|
||||
const response = await call(
|
||||
'agentSessionAttachment.uploadStart',
|
||||
{ sessionId: 'session-alpha', name: 'shot.png', byteLength: 3 },
|
||||
{ clientKind: 'runtime', clientCapabilities: [] }
|
||||
)
|
||||
expect(response).toMatchObject({
|
||||
ok: false,
|
||||
error: { message: expect.stringContaining('structured_agent_session_unsupported') }
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses a declared size over the attachment limit before storing anything', async () => {
|
||||
const response = await call(
|
||||
'agentSessionAttachment.uploadStart',
|
||||
{ sessionId: 'session-alpha', name: 'big.bin', byteLength: 51 * 1024 * 1024 },
|
||||
CLIENT_A
|
||||
)
|
||||
expect(response.ok).toBe(false)
|
||||
})
|
||||
|
||||
it("keeps one client's upload out of another's reach", async () => {
|
||||
const { uploadId } = result<{ uploadId: string }>(
|
||||
await call(
|
||||
@@ -175,18 +145,6 @@ describe('agentSessionAttachment.*', () => {
|
||||
expect(store.isUploadInFlight(uploadId)).toBe(true)
|
||||
})
|
||||
|
||||
it('refuses an upload for a chat this host does not hold', async () => {
|
||||
const response = await call(
|
||||
'agentSessionAttachment.uploadStart',
|
||||
{ sessionId: 'session-elsewhere', name: 'a.txt', byteLength: 1 },
|
||||
CLIENT_A
|
||||
)
|
||||
expect(response).toMatchObject({
|
||||
ok: false,
|
||||
error: { message: expect.stringContaining('not on this host') }
|
||||
})
|
||||
})
|
||||
|
||||
it('answers a remote preview of an image over 3 MiB with a small refusal, not an oversized reply', async () => {
|
||||
const path = await uploadBytes('big.png', Buffer.alloc(3.5 * 1024 * 1024, 7))
|
||||
const replies: string[] = []
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { OrcaRuntimeService } from '../../../orca-runtime'
|
||||
import { MOBILE_SNAPSHOT_BYTE_BUDGET } from '../../../scrollback-limits'
|
||||
import { buildSnapshotFrameMeta } from './terminal-snapshot-payload'
|
||||
|
||||
import { serializeBudgetedMobileSnapshot } from './terminal-snapshot-publication'
|
||||
import { isMovedPaneHistorySessionId } from '../../../../../shared/orcad-migration/orcad-migration-terminal-history'
|
||||
|
||||
function historyRuntime(bytesPerRow: number): Pick<OrcaRuntimeService, 'serializeTerminalBuffer'> {
|
||||
return {
|
||||
@@ -19,15 +18,6 @@ function historyRuntime(bytesPerRow: number): Pick<OrcaRuntimeService, 'serializ
|
||||
}
|
||||
|
||||
describe('subscribe snapshot scrollback (#20158)', () => {
|
||||
it('serializes history for every subscriber, not a screen-only image', async () => {
|
||||
const runtime = historyRuntime(10)
|
||||
const serialized = await serializeBudgetedMobileSnapshot(runtime, 'pty-1')
|
||||
expect(runtime.serializeTerminalBuffer).toHaveBeenCalledTimes(1)
|
||||
expect(runtime.serializeTerminalBuffer).toHaveBeenCalledWith('pty-1', { scrollbackRows: 1000 })
|
||||
expect(serialized?.scrollbackRows).toBe(1000)
|
||||
expect(serialized?.data).toBe(`${'h'.repeat(10_000)}SCREEN`)
|
||||
})
|
||||
|
||||
it('steps down the row ladder when history is over the byte budget', async () => {
|
||||
// 1000 rows is over 512 KiB, 500 rows is not.
|
||||
const bytesPerRow = Math.floor(MOBILE_SNAPSHOT_BYTE_BUDGET / 600)
|
||||
@@ -49,34 +39,4 @@ describe('subscribe snapshot of a WSL-moved pane', () => {
|
||||
(await serializeBudgetedMobileSnapshot(wide, 'pty-1', undefined, 5000))?.scrollbackRows
|
||||
).toBe(1000)
|
||||
})
|
||||
|
||||
it('names only moved panes by their session id', () => {
|
||||
expect(isMovedPaneHistorySessionId('repo::/w@@moved-0123456789abcdef')).toBe(true)
|
||||
expect(isMovedPaneHistorySessionId('repo::/w@@a1b2c3d4')).toBe(false)
|
||||
expect(isMovedPaneHistorySessionId('moved-0123456789abcdef')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('SnapshotStart scrollbackRows', () => {
|
||||
const base = { kind: 'scrollback' as const, cols: 80, rows: 24, data: '' }
|
||||
|
||||
it('publishes how many history rows the image carries, including zero', () => {
|
||||
expect(buildSnapshotFrameMeta({ ...base, scrollbackRows: 1000 }).scrollbackRows).toBe(1000)
|
||||
expect(buildSnapshotFrameMeta({ ...base, scrollbackRows: 0 }).scrollbackRows).toBe(0)
|
||||
})
|
||||
|
||||
it('omits the field when the publisher does not know, so the client reads it as unknown', () => {
|
||||
expect('scrollbackRows' in buildSnapshotFrameMeta(base)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('snapshot frame title', () => {
|
||||
const base = { kind: 'scrollback' as const, cols: 80, rows: 24, data: '' }
|
||||
|
||||
it("carries the image's title only with the seq that orders it", () => {
|
||||
expect(buildSnapshotFrameMeta({ ...base, seq: 7, lastTitle: 'Claude' }).lastTitle).toBe(
|
||||
'Claude'
|
||||
)
|
||||
expect('lastTitle' in buildSnapshotFrameMeta({ ...base, lastTitle: 'Claude' })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -31,35 +31,6 @@ describe('terminal agent send guard', () => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('rechecks a transient no-agent result before refusing a guarded send', async () => {
|
||||
vi.useFakeTimers()
|
||||
const getTerminalAgentStatus = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce({ handle: 'terminal-1', isRunningAgent: false, status: null })
|
||||
.mockResolvedValue({ handle: 'terminal-1', isRunningAgent: true, status: 'working' })
|
||||
const runtime = stubRuntime({
|
||||
resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }),
|
||||
getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }),
|
||||
getTerminalAgentStatus,
|
||||
sendTerminal: vi.fn().mockResolvedValue({
|
||||
handle: 'terminal-1',
|
||||
accepted: true,
|
||||
bytesWritten: 1
|
||||
})
|
||||
})
|
||||
const responsePromise = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }).dispatch(
|
||||
guardedSendRequest()
|
||||
)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(150)
|
||||
|
||||
await expect(responsePromise).resolves.toMatchObject({
|
||||
ok: true,
|
||||
result: { send: { accepted: true, bytesWritten: 1 } }
|
||||
})
|
||||
expect(getTerminalAgentStatus).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('rechecks a transient no-agent result immediately before the PTY write', async () => {
|
||||
vi.useFakeTimers()
|
||||
const getTerminalAgentStatus = vi
|
||||
|
||||
@@ -69,33 +69,6 @@ describe('a runtime start in a folder workspace on a stopped WSL distro (E9)', (
|
||||
expect(statsInUserAct).toEqual([true])
|
||||
})
|
||||
|
||||
it('treats a deduplicated CLI create as the user act too', async () => {
|
||||
const run = vi.fn(async () => ({ handle: 'term-1' }))
|
||||
await makeRuntime().dedupeTerminalCreate(
|
||||
'local',
|
||||
`id:${TEST_FOLDER_WORKSPACE_KEY}`,
|
||||
'mutation-1',
|
||||
false,
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the dedupe returns `run`'s result untouched; only the launch scope is under test.
|
||||
run as never,
|
||||
{ wslUserAct: true }
|
||||
)
|
||||
expect(statsInUserAct).toEqual([true])
|
||||
expect(run).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('checks the folder as the user act for an agent-session create', async () => {
|
||||
await makeRuntime()
|
||||
.createAgentSession({
|
||||
clientOperationId: `${Date.now()}-0123456789abcdef0123456789abcdef`,
|
||||
worktree: `id:${TEST_FOLDER_WORKSPACE_KEY}`,
|
||||
agent: 'claude'
|
||||
})
|
||||
// Later launch steps are out of scope; only the folder check's act is under test.
|
||||
.catch(() => undefined)
|
||||
expect(statsInUserAct[0]).toBe(true)
|
||||
})
|
||||
|
||||
it('checks the folder as the user act for a resume the user asked for', async () => {
|
||||
await makeRuntime().resumeAgentSessionInWorkspace(TEST_FOLDER_WORKSPACE_KEY, {
|
||||
agent: 'claude',
|
||||
@@ -106,19 +79,6 @@ describe('a runtime start in a folder workspace on a stopped WSL distro (E9)', (
|
||||
expect(statsInUserAct[0]).toBe(true)
|
||||
})
|
||||
|
||||
it('checks the folder as the user act for an explicit agent-session ensure', async () => {
|
||||
await makeRuntime()
|
||||
.ensureAgentSession({
|
||||
kind: 'explicit',
|
||||
worktree: `id:${TEST_FOLDER_WORKSPACE_KEY}`,
|
||||
agent: 'claude',
|
||||
providerSession: { key: 'session_id', id: 'provider-session-1' }
|
||||
})
|
||||
// Later launch steps are out of scope; only the folder check's act is under test.
|
||||
.catch(() => undefined)
|
||||
expect(statsInUserAct[0]).toBe(true)
|
||||
})
|
||||
|
||||
it('holds background work with Start, naming the distro, without touching the folder', async () => {
|
||||
await expect(
|
||||
makeRuntime().resolveTerminalWorkspaceLaunchScope(`id:${TEST_FOLDER_WORKSPACE_KEY}`)
|
||||
|
||||
@@ -28,55 +28,6 @@ describe('runtime metadata', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('writes and reads runtime metadata atomically', () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-metadata-'))
|
||||
tempDirs.push(userDataPath)
|
||||
|
||||
writeRuntimeMetadata(userDataPath, {
|
||||
runtimeId: 'rt_123',
|
||||
pid: 42,
|
||||
transports: [
|
||||
{
|
||||
kind: 'unix',
|
||||
endpoint: '/tmp/orca.sock'
|
||||
}
|
||||
],
|
||||
authToken: 'secret',
|
||||
startedAt: 100
|
||||
})
|
||||
|
||||
expect(readRuntimeMetadata(userDataPath)).toEqual({
|
||||
runtimeId: 'rt_123',
|
||||
pid: 42,
|
||||
transports: [
|
||||
{
|
||||
kind: 'unix',
|
||||
endpoint: '/tmp/orca.sock'
|
||||
}
|
||||
],
|
||||
authToken: 'secret',
|
||||
startedAt: 100
|
||||
})
|
||||
})
|
||||
|
||||
it('clears the runtime metadata file', () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-metadata-'))
|
||||
tempDirs.push(userDataPath)
|
||||
|
||||
writeRuntimeMetadata(userDataPath, {
|
||||
runtimeId: 'rt_123',
|
||||
pid: 42,
|
||||
transports: [],
|
||||
authToken: null,
|
||||
startedAt: 100
|
||||
})
|
||||
|
||||
clearRuntimeMetadata(userDataPath)
|
||||
|
||||
expect(readRuntimeMetadata(userDataPath)).toBeNull()
|
||||
expect(getRuntimeMetadataPath(userDataPath)).toContain('orca-runtime.json')
|
||||
})
|
||||
|
||||
describe('clearRuntimeMetadataIfOwned', () => {
|
||||
it('clears metadata when pid and runtimeId both match', () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-metadata-'))
|
||||
@@ -132,14 +83,6 @@ describe('runtime metadata', () => {
|
||||
runtimeId: 'rt_replacement'
|
||||
})
|
||||
})
|
||||
|
||||
it('is a no-op when no metadata exists', () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-metadata-'))
|
||||
tempDirs.push(userDataPath)
|
||||
|
||||
expect(() => clearRuntimeMetadataIfOwned(userDataPath, 42, 'rt_owner')).not.toThrow()
|
||||
expect(readRuntimeMetadata(userDataPath)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
it.runIf(process.platform !== 'win32')(
|
||||
|
||||
@@ -11,8 +11,7 @@ vi.mock('../ssh/orcad-retained-source', () => ({
|
||||
visibleFolderWorkspaces: vi.fn(() => [])
|
||||
}))
|
||||
|
||||
const { runtimeHiddenHostIds, runtimeHiddenRepos, runtimeVisibleRepos } =
|
||||
await import('./runtime-visible-catalog')
|
||||
const { runtimeHiddenHostIds, runtimeHiddenRepos } = await import('./runtime-visible-catalog')
|
||||
|
||||
const sshTarget = { id: 'target-1', label: 'dev', host: 'dev', port: 22, username: 'dev' }
|
||||
const repo = (id: string, connectionId?: string): Repo => ({
|
||||
@@ -29,30 +28,6 @@ const storeWith = (repos: Repo[], withTargets: boolean) => ({
|
||||
})
|
||||
|
||||
describe('runtime visible catalog', () => {
|
||||
it('lists what the desktop shows and names the rest as hidden', () => {
|
||||
const all = [repo('local'), repo('retained')]
|
||||
visibleRepos.mockImplementation((store) => store.getRepos().filter((r) => r.id !== 'retained'))
|
||||
const store = storeWith(all, true)
|
||||
expect(runtimeVisibleRepos(store).map((r) => r.id)).toEqual(['local'])
|
||||
expect(runtimeHiddenRepos(store).hasRepo(all[1]!)).toBe(true)
|
||||
expect(runtimeHiddenRepos(store).hasRepo(all[0]!)).toBe(false)
|
||||
})
|
||||
|
||||
it('treats a store with no SSH targets (headless orcad) as hiding nothing of its own', () => {
|
||||
visibleRepos.mockImplementation((store) => {
|
||||
expect(store.getSshTargets()).toEqual([])
|
||||
return store.getRepos()
|
||||
})
|
||||
const store = storeWith([repo('a')], false)
|
||||
expect(runtimeVisibleRepos(store)).toHaveLength(1)
|
||||
expect(runtimeHiddenRepos(store).size).toBe(0)
|
||||
})
|
||||
|
||||
it('lists nothing without a store', () => {
|
||||
expect(runtimeVisibleRepos(null)).toEqual([])
|
||||
expect(runtimeHiddenRepos(null).size).toBe(0)
|
||||
})
|
||||
|
||||
it('hides a moved local row by host while the WSL host row with the same id stays listed', () => {
|
||||
const local = repo('moved')
|
||||
const onHost: Repo = { ...repo('moved'), executionHostId: 'runtime:wsl-ubuntu' }
|
||||
@@ -65,22 +40,6 @@ describe('runtime visible catalog', () => {
|
||||
expect(hidden.hasWorktree({ repoId: 'moved', hostId: 'runtime:wsl-ubuntu' })).toBe(false)
|
||||
})
|
||||
|
||||
it('names a host known only through hidden rows, but never this machine', () => {
|
||||
visibleRepos.mockImplementation((store) =>
|
||||
store.getRepos().filter((r) => r.id !== 'retained' && r.id !== 'moved-local')
|
||||
)
|
||||
const store = storeWith(
|
||||
[
|
||||
repo('retained', 'target-1'),
|
||||
repo('moved-local'),
|
||||
repo('shared-a', 'target-2'),
|
||||
repo('shared-b', 'target-2')
|
||||
],
|
||||
true
|
||||
)
|
||||
expect([...runtimeHiddenHostIds(store)]).toEqual(['ssh:target-1'])
|
||||
})
|
||||
|
||||
it('keeps a host that still has a visible row', () => {
|
||||
visibleRepos.mockImplementation((store) => store.getRepos().filter((r) => r.id !== 'a'))
|
||||
const store = storeWith([repo('a', 'target-2'), repo('b', 'target-2')], true)
|
||||
|
||||
@@ -153,23 +153,6 @@ describe('worker-start --terminal names a chat', () => {
|
||||
expect(turnText(worker.turns[1]!)).toContain(dispatchId)
|
||||
})
|
||||
|
||||
it("reads the start as unknown when the chat's agent has not taken the task within the wait", async () => {
|
||||
await openChat(COORDINATOR)
|
||||
await openChat(PEER_CHAT)
|
||||
const { taskId } = await coordinatorRunAndTask()
|
||||
// The settlement wait running out, as for an agent still starting.
|
||||
vi.spyOn(host, 'waitForSendSettlement').mockResolvedValue(undefined)
|
||||
|
||||
const receipt = await startWorker({ task: taskId })
|
||||
|
||||
expect(receipt).toMatchObject({
|
||||
state: 'outcome_unknown',
|
||||
turnStart: 'unobserved',
|
||||
lastError: expect.stringContaining("the chat's agent had not started to take it")
|
||||
})
|
||||
expect(db.getWorkerDispatch(String(receipt.dispatchId))?.state).toBe('start_unknown')
|
||||
})
|
||||
|
||||
it('is stopped and abandoned without closing or interrupting the chat', async () => {
|
||||
await openChat(COORDINATOR)
|
||||
const worker = await openChat(PEER_CHAT)
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { WorkspaceSessionState } from '../../../../shared/workspace-session-state-types'
|
||||
import { getDefaultWorkspaceSession } from '../../../../shared/constants'
|
||||
import {
|
||||
PaneGridRecorder,
|
||||
PANE_GRID_FLUSH_BUDGET_MS,
|
||||
PANE_GRID_RECORD_DELAY_MS
|
||||
} from './pane-grid-recording'
|
||||
import { PaneGridRecorder, PANE_GRID_FLUSH_BUDGET_MS } from './pane-grid-recording'
|
||||
|
||||
const WORKSPACE = 'repo-1::/repo'
|
||||
|
||||
@@ -42,53 +38,6 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
describe('PaneGridRecorder', () => {
|
||||
it('writes one grid per resize burst, the last one, to the pane showing the terminal', async () => {
|
||||
vi.useFakeTimers()
|
||||
const apply = vi.fn(async () => ({ ok: true }))
|
||||
const recorder = new PaneGridRecorder({ sessions: () => [sessionBinding('pty-1')], apply })
|
||||
|
||||
recorder.record('pty-1', { cols: 80, rows: 24 })
|
||||
recorder.record('pty-1', { cols: 100, rows: 30 })
|
||||
await vi.advanceTimersByTimeAsync(PANE_GRID_RECORD_DELAY_MS - 1)
|
||||
expect(apply).not.toHaveBeenCalled()
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
|
||||
expect(apply).toHaveBeenCalledTimes(1)
|
||||
expect(apply).toHaveBeenCalledWith({
|
||||
type: 'setPaneGrid',
|
||||
workspace: WORKSPACE,
|
||||
tabId: 'tab-1',
|
||||
leafId: 'leaf-1',
|
||||
grid: { cols: 100, rows: 30 }
|
||||
})
|
||||
})
|
||||
|
||||
it('writes nothing for a terminal no pane shows, or an unmeasured grid', async () => {
|
||||
vi.useFakeTimers()
|
||||
const apply = vi.fn(async () => ({ ok: true }))
|
||||
const recorder = new PaneGridRecorder({ sessions: () => [sessionBinding('pty-1')], apply })
|
||||
|
||||
recorder.record('pty-other', { cols: 80, rows: 24 })
|
||||
recorder.record('pty-1', { cols: 0, rows: 0 })
|
||||
await vi.advanceTimersByTimeAsync(PANE_GRID_RECORD_DELAY_MS)
|
||||
|
||||
expect(apply).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('writes a waiting grid at once on flush, and has nothing to flush after', async () => {
|
||||
vi.useFakeTimers()
|
||||
const apply = vi.fn(async () => ({ ok: true }))
|
||||
const recorder = new PaneGridRecorder({ sessions: () => [sessionBinding('pty-1')], apply })
|
||||
|
||||
recorder.record('pty-1', { cols: 90, rows: 20 })
|
||||
await recorder.flush()
|
||||
|
||||
expect(apply).toHaveBeenCalledTimes(1)
|
||||
expect(recorder.flush()).toBeNull()
|
||||
await vi.advanceTimersByTimeAsync(PANE_GRID_RECORD_DELAY_MS)
|
||||
expect(apply).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('lets a quit go on once its budget is spent while a grid write hangs', async () => {
|
||||
vi.useFakeTimers()
|
||||
const apply = vi.fn(() => new Promise<never>(() => {}))
|
||||
|
||||
@@ -2,9 +2,7 @@ import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
parseWslInspectPathsOutput,
|
||||
parseWslListEntriesOutput,
|
||||
WslEnumerationProtocolError,
|
||||
WSL_INSPECT_PATHS_SCRIPT,
|
||||
WSL_LIST_ENTRIES_SCRIPT
|
||||
WslEnumerationProtocolError
|
||||
} from './wsl-enumeration-protocol'
|
||||
|
||||
const NUL = '\0'
|
||||
@@ -28,12 +26,6 @@ describe('parseWslListEntriesOutput', () => {
|
||||
expect(listings.get(directories[1])).toEqual([])
|
||||
})
|
||||
|
||||
it('reports an absent directory as an empty listing rather than a missing key', () => {
|
||||
const listings = parseWslListEntriesOutput('', ['/a', '/b'])
|
||||
expect([...listings.keys()]).toEqual(['/a', '/b'])
|
||||
expect(listings.get('/a')).toEqual([])
|
||||
})
|
||||
|
||||
it('refuses an unknown record kind instead of guessing', () => {
|
||||
expect(() => parseWslListEntriesOutput(records('X', '0'), ['/a'])).toThrow(
|
||||
WslEnumerationProtocolError
|
||||
@@ -76,29 +68,3 @@ describe('parseWslInspectPathsOutput', () => {
|
||||
).toThrow(WslEnumerationProtocolError)
|
||||
})
|
||||
})
|
||||
|
||||
describe('guest scripts', () => {
|
||||
it('classify a symlink before following it, so a broken link is not "missing"', () => {
|
||||
expect(WSL_INSPECT_PATHS_SCRIPT.indexOf('-L "$path"')).toBeLessThan(
|
||||
WSL_INSPECT_PATHS_SCRIPT.indexOf('-d "$path"')
|
||||
)
|
||||
expect(WSL_LIST_ENTRIES_SCRIPT.indexOf('-L "$entry"')).toBeLessThan(
|
||||
WSL_LIST_ENTRIES_SCRIPT.indexOf('-d "$entry"')
|
||||
)
|
||||
})
|
||||
|
||||
it('reads mtime without dereferencing, matching WSL discovery', () => {
|
||||
expect(WSL_INSPECT_PATHS_SCRIPT).toContain(`stat -c '%Y' -- "$path"`)
|
||||
expect(WSL_INSPECT_PATHS_SCRIPT).not.toContain('stat -L')
|
||||
})
|
||||
|
||||
it('takes every path positionally rather than interpolating it into the script', () => {
|
||||
expect(WSL_LIST_ENTRIES_SCRIPT).toContain('for dir in "$@"; do')
|
||||
expect(WSL_INSPECT_PATHS_SCRIPT).toContain('for path in "$@"; do')
|
||||
})
|
||||
|
||||
it('marks an unreadable directory instead of listing it as empty', () => {
|
||||
expect(WSL_LIST_ENTRIES_SCRIPT).toContain('if ! [ -r "$dir" ]; then')
|
||||
expect(WSL_LIST_ENTRIES_SCRIPT).toContain(`printf 'X\\0'`)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import type { SkillScanRoot } from './skill-discovery-sources'
|
||||
import { buildWslSkillDiscoveryCommand, parseWslSkillDiscoveryOutput } from './skill-discovery-wsl'
|
||||
import { parseWslSkillDiscoveryOutput } from './skill-discovery-wsl'
|
||||
|
||||
const homeRoot: SkillScanRoot = {
|
||||
id: 'home-codex',
|
||||
@@ -71,63 +72,6 @@ describe('WSL skill discovery', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('builds a distro-side scan for enumeration, reads, and canonical identity', () => {
|
||||
const script = buildWslSkillDiscoveryCommand([
|
||||
{ ...repoRoot, path: "/work/alice's project/.agents/skills" }
|
||||
])
|
||||
|
||||
expect(script).toContain('find -L "$root_path"')
|
||||
expect(script).toContain('realpath -- "$skill_file"')
|
||||
expect(script).toContain('head -c 262144 -- "$skill_file"')
|
||||
expect(script).toContain(`'/work/alice'\\''s project/.agents/skills'`)
|
||||
})
|
||||
|
||||
it('filters requested names before reading skill payloads', () => {
|
||||
const script = buildWslSkillDiscoveryCommand([homeRoot], ['Orchestration', 'computer-use'])
|
||||
|
||||
expect(script).toContain("'orchestration'|'computer-use') return 0")
|
||||
expect(script).toContain('local normalized_name=${1,,}')
|
||||
expect(script).toContain('metadata_name_known=0')
|
||||
expect(script).toContain('IFS= read -r -n "$remaining" line || read_status=$?')
|
||||
expect(script).toContain('[ "$line_length" -ge "$remaining" ] && return')
|
||||
expect(script).toContain('[[ "$candidate_name" =~ $non_ascii_pattern ]] && continue')
|
||||
expect(script).toContain("line=${line#$'\\xEF\\xBB\\xBF'}")
|
||||
expect(script).toContain('if [ "$metadata_name_known" -eq 1 ]; then')
|
||||
expect(script).toContain('done < "$1"')
|
||||
expect(script).not.toContain("awk '")
|
||||
expect(script).not.toContain("tr '[:upper:]'")
|
||||
expect(script.indexOf('matches_requested_name "$metadata_name" || continue')).toBeLessThan(
|
||||
script.indexOf('encoded_markdown=$(head')
|
||||
)
|
||||
})
|
||||
|
||||
it('filters classified source kinds while parsing', () => {
|
||||
const markdown = Buffer.from('---\nname: Bundled\n---\n').toString('base64')
|
||||
const output = [
|
||||
record('R', '0', '1'),
|
||||
record(
|
||||
'S',
|
||||
'0',
|
||||
'/home/alice/.codex/skills/.system/bundled/SKILL.md',
|
||||
'/home/alice/.codex/skills/.system/bundled/SKILL.md',
|
||||
'1700000000',
|
||||
markdown
|
||||
)
|
||||
].join('')
|
||||
|
||||
expect(parseWslSkillDiscoveryOutput(output, [homeRoot], 42, ['home']).skills).toEqual([])
|
||||
expect(parseWslSkillDiscoveryOutput(output, [homeRoot], 42, []).skills).toHaveLength(1)
|
||||
expect(parseWslSkillDiscoveryOutput(output, [homeRoot], 42, [], [' ']).skills).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('keeps ASCII prefiltering for mixed-locale requested names', () => {
|
||||
const script = buildWslSkillDiscoveryCommand([homeRoot], ['orchestration', 'hébergement'])
|
||||
|
||||
expect(script).toContain("'orchestration') return 0")
|
||||
expect(script).not.toContain('hébergement) return 0')
|
||||
expect(script).toContain('is_ascii_name "$directory_name"')
|
||||
})
|
||||
|
||||
it('uses the TypeScript summary parser for uncertain WSL name candidates', () => {
|
||||
const blockName = Buffer.from('\uFEFF---\nname: >-\n Agent\n Orchestration\n---\n').toString(
|
||||
'base64'
|
||||
@@ -163,36 +107,4 @@ describe('WSL skill discovery', () => {
|
||||
).skills.map((skill) => skill.name)
|
||||
).toEqual(['Agent Orchestration', 'Computer Use'])
|
||||
})
|
||||
|
||||
it('rejects malformed host responses instead of reporting an empty scan', () => {
|
||||
expect(() => parseWslSkillDiscoveryOutput(record('S', '9'), [homeRoot])).toThrow(
|
||||
'unknown source'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('reuses one source collator while preserving locale, lexical numbers, and stable ties', () => {
|
||||
const labels = Array.from(
|
||||
{ length: 200 },
|
||||
(_, index) =>
|
||||
['éclair', 'Eclair', 'item2', 'item10', 'Ångström', 'zebra', 'İstanbul'][index % 7]
|
||||
)
|
||||
const roots = labels.map((label, index) => ({ ...homeRoot, id: String(index), label }))
|
||||
const expected = [...roots].sort((a, b) =>
|
||||
// ast-grep-ignore: no-repeated-collator -- Preserve the old comparator as the parity oracle.
|
||||
a.label.localeCompare(b.label, undefined, { sensitivity: 'base' })
|
||||
)
|
||||
const NativeCollator = Intl.Collator
|
||||
const construct = vi.spyOn(Intl, 'Collator').mockImplementation(function (locales, options) {
|
||||
return new NativeCollator(locales, options)
|
||||
})
|
||||
const localeCompare = vi.spyOn(String.prototype, 'localeCompare')
|
||||
try {
|
||||
const result = parseWslSkillDiscoveryOutput('', roots, 42)
|
||||
expect(result.sources.map((source) => source.id)).toEqual(expected.map((root) => root.id))
|
||||
expect(construct).toHaveBeenCalledExactlyOnceWith(undefined, { sensitivity: 'base' })
|
||||
expect(localeCompare).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
vi.restoreAllMocks()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -42,13 +42,6 @@ describe('getRemoteHeadBranchName', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('returns null for a missing remote HEAD without resolving origin', async () => {
|
||||
gitExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' })
|
||||
await expect(getRemoteHeadBranchName('/repo', 'upstream')).resolves.toBeNull()
|
||||
await expect(getRemoteHeadBranchName('/repo', 'upstream')).resolves.toBeNull()
|
||||
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('ignores a symbolic HEAD pointing into another remote', async () => {
|
||||
gitExecFileAsyncMock.mockResolvedValue({
|
||||
stdout: 'refs/remotes/upstream/HEAD\0refs/remotes/origin/main\n',
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
|
||||
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
|
||||
|
||||
import { tmpdir } from 'node:os'
|
||||
import type * as Os from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
@@ -77,20 +78,6 @@ describe('OpenAI speech API key store', () => {
|
||||
expect(() => store.readOpenAiSpeechApiKey()).toThrow('OpenAI API key could not be decrypted')
|
||||
})
|
||||
|
||||
it('reports a stored key this host can decrypt as usable', async () => {
|
||||
writeStoredOpenAiKey('encrypted-key')
|
||||
const store = await loadStoreModule()
|
||||
expect(store.canReadOpenAiSpeechApiKey()).toBe(true)
|
||||
})
|
||||
|
||||
it('decrypts only when the key is read for an API request', async () => {
|
||||
writeStoredOpenAiKey('encrypted-key')
|
||||
const store = await loadStoreModule()
|
||||
|
||||
expect(store.readOpenAiSpeechApiKey()).toBe('encrypted-key')
|
||||
expect(safeStorageMock.decryptString).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('caches the decrypted key so repeated dictations do not repeatedly touch safeStorage', async () => {
|
||||
writeStoredOpenAiKey('encrypted-key')
|
||||
const store = await loadStoreModule()
|
||||
@@ -99,21 +86,4 @@ describe('OpenAI speech API key store', () => {
|
||||
expect(store.readOpenAiSpeechApiKey()).toBe('encrypted-key')
|
||||
expect(safeStorageMock.decryptString).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('uses the in-memory key after save without decrypting from safeStorage', async () => {
|
||||
const store = await loadStoreModule()
|
||||
|
||||
store.saveOpenAiSpeechApiKey('saved-key')
|
||||
|
||||
expect(store.readOpenAiSpeechApiKey()).toBe('saved-key')
|
||||
expect(safeStorageMock.decryptString).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports missing status without creating storage files', async () => {
|
||||
const store = await loadStoreModule()
|
||||
|
||||
expect(store.hasOpenAiSpeechApiKey()).toBe(false)
|
||||
expect(existsSync(join(tempHome, '.orca'))).toBe(false)
|
||||
expect(safeStorageMock.decryptString).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -16,16 +16,6 @@ Host *
|
||||
expect(mayClaim(config, 'prod')).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps a Host block that names the alias authoritative', () => {
|
||||
const config = `
|
||||
Host *
|
||||
ProxyCommand nc %h %p
|
||||
Host prod
|
||||
HostName prod.internal
|
||||
`
|
||||
expect(mayClaim(config, 'prod')).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps a glob that reaches the alias authoritative', () => {
|
||||
// parseSshConfig drops these, which is why the claim check cannot reuse it.
|
||||
const config = `
|
||||
@@ -56,24 +46,4 @@ Match host prod
|
||||
expect(mayClaim('Host * !prod\n ForwardAgent yes\n', 'stage')).toBe(true)
|
||||
expect(mayClaim('Host * !prod\n ForwardAgent yes\n', 'prod')).toBe(true)
|
||||
})
|
||||
|
||||
it('still proves absence when no group negates', () => {
|
||||
expect(mayClaim('Host *\n ForwardAgent yes\nHost prod\n User ops\n', 'stage')).toBe(false)
|
||||
})
|
||||
|
||||
it('reads an unreadable config as uncertainty, not absence', () => {
|
||||
expect(sshConfigMayClaimAlias('prod', null)).toBe(true)
|
||||
})
|
||||
|
||||
it('reads an empty alias as uncertainty', () => {
|
||||
expect(sshConfigMayClaimAlias('', parseSshConfigAliasClaims('Host *\n'))).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseSshConfigAliasClaims', () => {
|
||||
it('retains the raw pattern groups and flags Match blocks', () => {
|
||||
expect(
|
||||
parseSshConfigAliasClaims('Host a b* # comment\n User x\nMatch final\n User y\n')
|
||||
).toEqual({ hostPatternGroups: [['a', 'b*']], hasMatchBlock: true })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
canRunHostileHostCell,
|
||||
forbiddenToolActions,
|
||||
forbiddenToolsFor,
|
||||
forbiddenToolShimScript,
|
||||
HOSTILE_HOST_CELLS,
|
||||
isLocalSshdCell,
|
||||
selectHostileHostCells,
|
||||
type DockerHostileHostCell,
|
||||
type HostileHostCell
|
||||
} from './ssh-hostile-host-cells'
|
||||
import { hostileHostDockerfile } from './ssh-hostile-host-test-fixture'
|
||||
|
||||
const LINUX = { platform: 'linux', arch: 'x64' } as const
|
||||
const MAC_ARM = { platform: 'darwin', arch: 'arm64' } as const
|
||||
const DOCKER_CELLS = HOSTILE_HOST_CELLS.filter(
|
||||
(candidate): candidate is DockerHostileHostCell => !isLocalSshdCell(candidate)
|
||||
)
|
||||
|
||||
function dockerCell(id: string): DockerHostileHostCell {
|
||||
const found = DOCKER_CELLS.find((candidate) => candidate.id === id)
|
||||
if (!found) {
|
||||
throw new Error(`no docker cell ${id}`)
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
function cell(id: string): HostileHostCell {
|
||||
const found = HOSTILE_HOST_CELLS.find((candidate) => candidate.id === id)
|
||||
if (!found) {
|
||||
throw new Error(`no cell ${id}`)
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
describe('hostile-host cells', () => {
|
||||
it('states a managed orcad expectation for every host the matrix runs', () => {
|
||||
expect(HOSTILE_HOST_CELLS.map((c) => [c.id, c.managed.runtime, c.managed.outcome])).toEqual([
|
||||
['debian10-glibc228', 'linux-x64-glibc', 'activated'],
|
||||
['almalinux8-glibc228', 'linux-x64-glibc', 'activated'],
|
||||
['alpine-musl', 'linux-x64-musl', 'activated'],
|
||||
['alpine-musl-no-libstdcxx', 'linux-x64-musl', 'unavailable'],
|
||||
['ubuntu2204-noexec-home', 'linux-x64-glibc', 'unavailable'],
|
||||
['centos7-glibc217', 'linux-x64-glibc217', 'activated'],
|
||||
['debian10-no-egress', 'linux-x64-glibc', 'activated'],
|
||||
['almalinux8-desktop-no-egress', 'linux-x64-glibc', 'activated'],
|
||||
['macos-arm64-local-sshd', 'darwin-arm64', 'activated'],
|
||||
['macos-x64-local-sshd', 'darwin-x64', 'activated']
|
||||
])
|
||||
})
|
||||
|
||||
it('pins every base image by digest and installs no compiler or host Node', () => {
|
||||
for (const { dockerfile } of DOCKER_CELLS) {
|
||||
for (const from of dockerfile.filter((line) => line.startsWith('FROM '))) {
|
||||
expect(from).toMatch(/@sha256:[0-9a-f]{64}\b/)
|
||||
}
|
||||
expect(dockerfile.join('\n')).not.toMatch(/\b(?:gcc|g\+\+|build-essential|nodejs|npm)\b/)
|
||||
}
|
||||
})
|
||||
|
||||
it('shims the toolchain and starts sshd in every image', () => {
|
||||
const dockerfile = hostileHostDockerfile(dockerCell('alpine-musl'))
|
||||
expect(dockerfile.startsWith('FROM alpine:3.20@sha256:')).toBe(true)
|
||||
expect(dockerfile).toContain('ln -sf orca-forbidden-tool /usr/local/bin/npm')
|
||||
expect(dockerfile).toContain('ln -sf orca-forbidden-tool /usr/local/bin/gcc')
|
||||
expect(dockerfile.trimEnd().endsWith('CMD ["/orca-entrypoint.sh"]')).toBe(true)
|
||||
})
|
||||
|
||||
it('selects named cells this machine can host and rejects unknown ones', () => {
|
||||
expect(selectHostileHostCells(undefined, HOSTILE_HOST_CELLS, LINUX)).toEqual(DOCKER_CELLS)
|
||||
expect(selectHostileHostCells(' ', HOSTILE_HOST_CELLS, LINUX)).toEqual(DOCKER_CELLS)
|
||||
expect(
|
||||
selectHostileHostCells('alpine-musl, centos7-glibc217', HOSTILE_HOST_CELLS, LINUX).map(
|
||||
(c) => c.id
|
||||
)
|
||||
).toEqual(['alpine-musl', 'centos7-glibc217'])
|
||||
expect(() => selectHostileHostCells('alpine-musl,solaris', HOSTILE_HOST_CELLS, LINUX)).toThrow(
|
||||
'Unknown hostile-host cells: solaris'
|
||||
)
|
||||
})
|
||||
|
||||
it('runs a macOS cell only on its own OS and arch, and no Docker cell there', () => {
|
||||
expect(selectHostileHostCells('', HOSTILE_HOST_CELLS, MAC_ARM).map((c) => c.id)).toEqual([
|
||||
'macos-arm64-local-sshd'
|
||||
])
|
||||
expect(
|
||||
selectHostileHostCells('macos-arm64-local-sshd', HOSTILE_HOST_CELLS, MAC_ARM).map((c) => c.id)
|
||||
).toEqual(['macos-arm64-local-sshd'])
|
||||
expect(() =>
|
||||
selectHostileHostCells('alpine-musl,macos-arm64-local-sshd', HOSTILE_HOST_CELLS, LINUX)
|
||||
).toThrow('cannot run on linux-x64: macos-arm64-local-sshd')
|
||||
expect(() =>
|
||||
selectHostileHostCells('macos-x64-local-sshd', HOSTILE_HOST_CELLS, MAC_ARM)
|
||||
).toThrow('cannot run on darwin-arm64: macos-x64-local-sshd')
|
||||
expect(canRunHostileHostCell(cell('macos-x64-local-sshd'), MAC_ARM)).toBe(false)
|
||||
expect(
|
||||
canRunHostileHostCell(cell('macos-x64-local-sshd'), { platform: 'darwin', arch: 'x64' })
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('forbids xattr only on the macOS runners', () => {
|
||||
expect(forbiddenToolsFor(cell('macos-arm64-local-sshd'))).toContain('xattr')
|
||||
expect(forbiddenToolsFor(cell('debian10-glibc228'))).not.toContain('xattr')
|
||||
})
|
||||
|
||||
it('writes a shim that logs its own name and arguments, then fails like a missing tool', () => {
|
||||
expect(forbiddenToolShimScript('/tmp/x/calls.log')).toBe(
|
||||
`#!/bin/sh\nprintf '%s %s\\n' "\${0##*/}" "$*" >> '/tmp/x/calls.log'\nexit 127\n`
|
||||
)
|
||||
})
|
||||
|
||||
it('reports logged installs and compiles but not version probes', () => {
|
||||
expect(forbiddenToolActions('npm install\n\ngcc -v\nnpm --version\nmake all\n')).toEqual([
|
||||
'npm install',
|
||||
'make all'
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -9,14 +9,12 @@ import {
|
||||
import {
|
||||
ORCAD_FENCE_LOST_MARKER,
|
||||
OrcadFenceLostError,
|
||||
isOrcadFenceLost,
|
||||
posixOrcadFenceGuard,
|
||||
runWithOrcadFence
|
||||
} from '../managed-server/activation/orcad-activation-fence-scope'
|
||||
import {
|
||||
isUnconfirmedSshCommandTermination,
|
||||
sshCommandExitError
|
||||
} from './remote-exec/remote-exec-command'
|
||||
|
||||
import { isUnconfirmedSshCommandTermination } from './remote-exec/remote-exec-command'
|
||||
|
||||
import { getRemoteHostPlatform } from './ssh-remote-platform'
|
||||
import type { OrcadHostTransport } from './orcad-host-transport'
|
||||
|
||||
@@ -86,14 +84,6 @@ describe('a fenced step through the real exec', () => {
|
||||
expect(error).toMatchObject({ exitCode: 1, stdout: 'boom\n' })
|
||||
})
|
||||
|
||||
it('lets a failed step fall back', async () => {
|
||||
const answer = await settledAfter(
|
||||
fenced(() => execOrcadRemoteOr(target, 'false', 'FALLBACK')),
|
||||
() => channel.exit(1, '')
|
||||
)
|
||||
expect(answer).toBe('FALLBACK')
|
||||
})
|
||||
|
||||
it('keeps a timed-out step unconfirmed, so the fence is not released under it', async () => {
|
||||
const settled = fenced(() => execOrcadRemoteOr(target, 'sleep 99', 'FALLBACK')).catch(
|
||||
(error: unknown) => error
|
||||
@@ -139,13 +129,3 @@ describe('a fenced state mutation through the real exec', () => {
|
||||
expect(error).toBeInstanceOf(OrcadFenceLostError)
|
||||
})
|
||||
})
|
||||
|
||||
describe('a Windows host op whose exit PowerShell flattened to 1', () => {
|
||||
it('is a lost fence only when the host script printed the marker', () => {
|
||||
const op = `powershell.exe -Command "& 'node.exe' 'host.js' --fence d t ${ORCAD_FENCE_LOST_MARKER}"`
|
||||
expect(isOrcadFenceLost(sshCommandExitError(op, 1, `${ORCAD_FENCE_LOST_MARKER}\r\n`))).toBe(
|
||||
true
|
||||
)
|
||||
expect(isOrcadFenceLost(sshCommandExitError(op, 1, 'ENOENT\r\n'))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
serializeOrcadMigrationValue,
|
||||
type OrcadMigrationCatalogPayload
|
||||
} from '../../shared/orcad-migration/orcad-migration-manifest'
|
||||
import type { OrcadMigrationCatalogPayload } from '../../shared/orcad-migration/orcad-migration-manifest'
|
||||
|
||||
import { isRecord } from '../../shared/orcad-migration/orcad-migration-manifest-fields'
|
||||
import { ownedEditorFileId } from '../../shared/workspace-session-pane-ownership'
|
||||
import {
|
||||
ORCAD_MIGRATION_PATH_FIELDS,
|
||||
ORCAD_MIGRATION_UNREWRITTEN_PATH_FIELDS,
|
||||
type OrcadMigrationPathFieldKind
|
||||
} from './orcad-migration-path-fields'
|
||||
|
||||
import {
|
||||
IDENTITY_ORCAD_MIGRATION_PATH_REWRITER,
|
||||
parseFieldLocation,
|
||||
rewriteOrcadMigrationPayloadPaths,
|
||||
type OrcadMigrationPathRewriter
|
||||
@@ -125,24 +122,7 @@ function valuesAt(node: unknown, steps: ReturnType<typeof parseFieldLocation>):
|
||||
return valuesAt(node[step.name], rest)
|
||||
}
|
||||
|
||||
function deepFreeze<T>(value: T): T {
|
||||
if (typeof value === 'object' && value !== null) {
|
||||
Object.values(value).forEach(deepFreeze)
|
||||
Object.freeze(value)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
describe('orcad migration path-rewrite stage', () => {
|
||||
it('is exact under the identity: same value, same bytes, same key order, input untouched', () => {
|
||||
const input = deepFreeze(payloadWithEveryField())
|
||||
const output = rewriteOrcadMigrationPayloadPaths(input, IDENTITY_ORCAD_MIGRATION_PATH_REWRITER)
|
||||
expect(output).not.toBe(input)
|
||||
expect(output).toEqual(input)
|
||||
expect(JSON.stringify(output)).toBe(JSON.stringify(input))
|
||||
expect(serializeOrcadMigrationValue(output)).toBe(serializeOrcadMigrationValue(input))
|
||||
})
|
||||
|
||||
// Guard against per-entry Object.keys calls that made 20k-key renames quadratic.
|
||||
it('walks a large keyed record in linear time', () => {
|
||||
const started = performance.now()
|
||||
@@ -150,27 +130,6 @@ describe('orcad migration path-rewrite stage', () => {
|
||||
expect(performance.now() - started).toBeLessThan(2_000)
|
||||
})
|
||||
|
||||
it('reaches every field the table names', () => {
|
||||
const input = deepFreeze(payloadWithEveryField())
|
||||
const output = rewriteOrcadMigrationPayloadPaths(input, MARKING)
|
||||
for (const field of ORCAD_MIGRATION_PATH_FIELDS) {
|
||||
const values = valuesAt(output, parseFieldLocation(field.at))
|
||||
expect(values, field.at).not.toEqual([])
|
||||
for (const value of values) {
|
||||
expect(value, field.at).not.toBe(SAMPLE[field.kind])
|
||||
expect(String(value), field.at).not.toMatch(/\/src\/|%2Fsrc%2F|^rel\//)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('names every location once, and never both rewrites and skips one', () => {
|
||||
const rewritten = ORCAD_MIGRATION_PATH_FIELDS.map((field) => field.at)
|
||||
expect(new Set(rewritten).size).toBe(rewritten.length)
|
||||
for (const skipped of ORCAD_MIGRATION_UNREWRITTEN_PATH_FIELDS) {
|
||||
expect(rewritten).not.toContain(skipped.at)
|
||||
}
|
||||
})
|
||||
|
||||
it('rewrites only the path half of composite ids', () => {
|
||||
const map = (kind: OrcadMigrationPathFieldKind, value: string): unknown => {
|
||||
const field = ORCAD_MIGRATION_PATH_FIELDS.find((entry) => entry.kind === kind)!
|
||||
|
||||
@@ -10,14 +10,6 @@ const route = (overrides: Partial<SshRoute> = {}): SshRoute => ({
|
||||
})
|
||||
|
||||
describe('sshRouteKey', () => {
|
||||
it('keeps aliases apart when a shared ProxyCommand names the alias with %n', () => {
|
||||
const proxy = { kind: 'proxy-command' as const, command: 'docker exec -i %n nc localhost 22' }
|
||||
|
||||
expect(sshRouteKey(route({ alias: 'dev1', proxy }))).not.toBe(
|
||||
sshRouteKey(route({ alias: 'dev2', proxy }))
|
||||
)
|
||||
})
|
||||
|
||||
it('matches a route whose tokens expand to the same command', () => {
|
||||
expect(
|
||||
sshRouteKey(route({ proxy: { kind: 'proxy-command', command: 'ssh bastion -W %h:%p' } }))
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user