test: remove 51 low-value suites (#42927)

* test: remove 51 low-value suites

* test: retire obsolete computer workflow targets

---------

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-15 18:48:14 -08:00
committed by GitHub
co-authored by OrcaWin
parent 37f57be29b
commit 8d802a17f4
60 changed files with 22 additions and 6343 deletions
-4
View File
@@ -14,10 +14,8 @@ on:
- 'config/scripts/native-build/windows/windows-rust-executable-build.mjs'
- 'config/scripts/native-build/windows/build-windows-cli-launcher.test.mjs'
- 'config/scripts/performance/macos-computer-owner/macos-computer-helper-owner-loss-benchmark.mjs'
- 'config/scripts/performance/macos-computer-owner/macos-computer-helper-owner-loss-group-recovery.test.mjs'
- 'config/scripts/performance/macos-computer-owner/macos-computer-helper-owner-loss-metrics.mjs'
- 'config/scripts/performance/macos-computer-owner/macos-computer-helper-owner-loss-processes.mjs'
- 'config/scripts/performance/macos-computer-owner/macos-computer-helper-owner-loss-processes.test.mjs'
- 'config/scripts/performance/macos-computer-owner/macos-computer-helper-owner-loss-trial-cleanup.mjs'
- 'config/scripts/runtime-verification/daemon-lifecycle/daemon-boot-smoke.mjs'
- 'config/scripts/runtime-verification/daemon-lifecycle/daemon-endpoint-handover-smoke.mjs'
@@ -91,8 +89,6 @@ jobs:
# Use shared Vitest config: bare invocation misses config/ and its timeout/Windows worker cap, breaking real csc.exe tests.
- run: >-
pnpm vitest run --config config/vitest.config.ts
config/scripts/performance/macos-computer-owner/macos-computer-helper-owner-loss-group-recovery.test.mjs
config/scripts/performance/macos-computer-owner/macos-computer-helper-owner-loss-processes.test.mjs
src/main/computer/sidecar-transport/sidecar-client.test.ts
src/main/computer/macos-native/macos-native-provider-client.test.ts
src/main/providers/shell-launch/windows/shell-preflight-runtime.windows.test.ts
@@ -50,11 +50,6 @@ jobs:
- uses: ./.github/actions/install-node-dependencies
with:
native-runtime: electron
- name: Owner-loss benchmark process cleanup
run: >-
pnpm vitest run
config/scripts/performance/macos-computer-owner/macos-computer-helper-owner-loss-group-recovery.test.mjs
config/scripts/performance/macos-computer-owner/macos-computer-helper-owner-loss-processes.test.mjs
# Why: the parallel launcher's cancellation tests are darwin-only and no
# other PR job runs on macOS.
- name: Parallel native build launcher cancellation
@@ -57,8 +57,3 @@ jobs:
src/main/updater/mac-install/updater-mac-quit-guard.test.ts
src/main/startup/quit/main-process-quit-update-veto.test.ts
src/main/window/main-window/main-window-state-lifecycle.test.ts
- name: Prove login-backed terminal writer census on the disposable runner
env:
ORCA_MACOS_LOGIN_CENSUS_CI: '1'
ORCA_BACKGROUND_LAUNCH: '1'
run: pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/agent-session/lifecycle/structured-agent-cli-writers.test.ts
-1
View File
@@ -859,7 +859,6 @@ jobs:
src/shared/shell/wsl/fish-wsl-cwd-report.node-pty.test.ts \
src/main/wsl/filesystem/wsl-sh-cwd-report.node-pty.test.ts \
src/shared/terminal/pty/ingress/pty-reply-echo-shapes.node-pty.test.ts \
src/shared/shell/launch/startup-shell-portability.live-shell.test.ts \
src/shared/shell/command-resolution/posix-command-path-lookup.test.ts
# Shards wait only for the plan, not preflight, which moves them about two minutes earlier.
File diff suppressed because one or more lines are too long
@@ -77,7 +77,6 @@
"config/scripts/preflight/changed-checks/lint-staged-worktree-backup.test.mjs": 278,
"config/scripts/localization/source-extraction/localization-extraction-call-syntax.test.mjs": 317,
"config/scripts/localization/extraction-policy/localization-extraction-change-scope.test.mjs": 732,
"config/scripts/performance/macos-computer-owner/macos-computer-helper-owner-loss-processes.test.mjs": 52,
"config/scripts/desktop-distribution/macos/macos-folder-usage-descriptions.test.mjs": 147,
"config/scripts/desktop-distribution/macos/macos-shipit-scheduling.test.mjs": 38,
"config/scripts/macos/terminal-host-bundle/macos-terminal-host-bundle.test.mjs": 182,
@@ -88,30 +87,23 @@
"config/scripts/mobile-web-app/shell/mobile-web-app-agent-icon-render.test.mjs": 591,
"config/scripts/mobile-web-app/shell/mobile-web-app-browser-pane-render.test.mjs": 239,
"config/scripts/mobile-web-app/shell/mobile-web-app-clipboard-image-resize-render.test.mjs": 422,
"config/scripts/mobile-web-app/shell/mobile-web-app-composer-sizing-render.test.mjs": 252,
"config/scripts/mobile-web-app/shell/mobile-web-app-drawer-render.test.mjs": 253,
"config/scripts/mobile-web-app/workspace/mobile-web-app-files-external-links.test.mjs": 126,
"config/scripts/mobile-web-app/workspace/mobile-web-app-files-render.test.mjs": 214,
"config/scripts/mobile-web-app/shell/mobile-web-app-frame-budget-sweep.test.ts": 210,
"config/scripts/mobile-web-app/shell/mobile-web-app-handoff-grants-render.test.mjs": 258,
"config/scripts/mobile-web-app/shell/mobile-web-app-held-press-render.test.mjs": 570,
"config/scripts/mobile-web-app/session/mobile-web-app-mermaid-render.test.mjs": 498,
"config/scripts/mobile-web-app/routing/mobile-web-app-module-closure-entrypoints.test.mjs": 109,
"config/scripts/mobile-web-app/session/mobile-web-app-native-chat-visual-links.test.mjs": 220,
"config/scripts/mobile-web-app/shell/mobile-web-app-native-parity-render.test.mjs": 253,
"config/scripts/mobile-web-app/routing/mobile-web-app-page-closure-families.test.mjs": 71,
"config/scripts/mobile-web-app/routing/mobile-web-app-page-grant-call-sites.test.mjs": 164,
"config/scripts/mobile-web-app/routing/mobile-web-app-push-subsystem-closure.test.mjs": 57,
"config/scripts/mobile-web-app/shell/mobile-web-app-render.test.mjs": 254,
"config/scripts/mobile-web-app/session/mobile-web-app-rich-markdown-render.test.mjs": 356,
"config/scripts/mobile-web-app/shell/mobile-web-app-safe-area-render.test.mjs": 314,
"config/scripts/mobile-web-app/session/mobile-web-app-screencast-lane-grant.test.mjs": 70,
"config/scripts/mobile-web-app/session/mobile-web-app-session-dictation-capture.test.mjs": 123,
"config/scripts/mobile-web-app/session/mobile-web-app-session-external-links.test.mjs": 142,
"config/scripts/mobile-web-app/session/mobile-web-app-session-media-picker.test.mjs": 164,
"config/scripts/mobile-web-app/session/mobile-web-app-session-render.test.mjs": 327,
"config/scripts/mobile-web-app/terminal/mobile-web-app-session-terminal-closure.test.mjs": 63,
"config/scripts/mobile-web-app/terminal/mobile-web-app-session-terminal-init.test.mjs": 221,
"config/scripts/mobile-web-app/session/mobile-web-app-session-webview-consumers.test.mjs": 55,
"config/scripts/mobile-web-app/workspace/mobile-web-app-source-control-external-links.test.mjs": 125,
"config/scripts/mobile-web-app/workspace/mobile-web-app-source-control-keyboard.test.mjs": 59,
@@ -126,8 +118,6 @@
"config/scripts/mobile-web-app/shell/mobile-web-app-text-input-discovery.test.mjs": 113,
"config/scripts/mobile-web-app/shell/mobile-web-app-working-spinner-render.test.mjs": 232,
"config/scripts/mobile-web-app/preview/mobile-web-app-html-preview-render.test.mjs": 333,
"config/scripts/mobile-web-app/preview/mobile-web-app-media-preview-render.test.mjs": 196,
"config/scripts/mobile-web-app/preview/mobile-web-app-svg-preview-render.test.mjs": 340,
"config/scripts/build/mobile-web-app/mobile-web-bundle-manifest.test.mjs": 126,
"config/scripts/build/mobile-web-app/mobile-web-bundle-serializer-parity.test.mjs": 112,
"config/scripts/build/mobile-web-app/mobile-web-page-routes.test.mjs": 129,
@@ -793,7 +783,6 @@
"src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.test.ts": 919,
"src/main/claude-accounts/sign-in/claude-sign-in-browser.test.ts": 314,
"src/main/claude-accounts/runtime-auth/keychain-config-directory-aliases.test.ts": 51,
"src/main/claude-usage/claude-usage-report-aggregation.test.ts": 57,
"src/main/claude-usage/persisted-source-authority.test.ts": 491,
"src/main/claude-usage/scanner-long-context.test.ts": 186,
"src/main/claude-usage/scanner-scan.test.ts": 295,
@@ -972,7 +961,6 @@
"src/main/codex/hooks/reconciliation/codex-real-home-hook-entries.test.ts": 543,
"src/main/codex/hooks/definitions/codex-real-home-hook-key-spellings.test.ts": 408,
"src/main/codex/hooks/reconciliation/codex-real-home-hook-removal.test.ts": 388,
"src/main/codex/configuration/homes/codex-real-home-path.test.ts": 76,
"src/main/codex/history/backfill/codex-session-backfill.test.ts": 310,
"src/main/codex/history/bridges/codex-session-bridge.test.ts": 118,
"src/main/codex/history/index/codex-session-index-heal.test.ts": 2722,
@@ -1579,7 +1567,6 @@
"src/main/ipc/pty/pty-controller-ownership-routing.test.ts": 4067,
"src/main/ipc/pty/pty-controller-spawn-admission.test.ts": 4904,
"src/main/ipc/pty/pty-daemon-spawn-session-identity.test.ts": 5120,
"src/main/ipc/pty/pty-management-async-io-health.test.ts": 423,
"src/main/ipc/pty/pty-pane-reservation-settlement.test.ts": 4089,
"src/main/ipc/pty/pty-pane-restart-replace.test.ts": 4301,
"src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts": 4173,
@@ -1716,7 +1703,6 @@
"src/main/managed-server/install/orcad-remote-decommission.test.ts": 434,
"src/main/managed-server/install/orcad-remote-launch-file-modes.test.ts": 400,
"src/main/managed-server/install/orcad-remote-launch-setsid.test.ts": 342,
"src/main/managed-server/install/orcad-remote-launch.test.ts": 319,
"src/main/managed-server/install/orcad-remote-node-runtime.test.ts": 248,
"src/main/managed-server/install/orcad-remote-readiness-wait.test.ts": 9063,
"src/main/managed-server/install/orcad-remote-runtime.test.ts": 488,
@@ -1769,7 +1755,6 @@
"src/main/native-chat/agent-session-timeline/provider-timeline-assembler-restart.test.ts": 576,
"src/main/native-chat/agent-session-timeline/provider-timeline-assembler-streams.test.ts": 757,
"src/main/native-chat/agent-session-timeline/provider-timeline-assembler-turns.test.ts": 809,
"src/main/native-chat/agent-session-timeline/provider-timeline-identity.test.ts": 52,
"src/main/native-chat/agent-session-wire/observations/testing/agent-session-current-requests.test.ts": 271,
"src/main/native-chat/agent-session-wire/publication/subscribers/testing/agent-session-delta-coalescer.test.ts": 61,
"src/main/native-chat/agent-session-wire/publication/history/testing/agent-session-history-byte-limits.test.ts": 858,
@@ -2034,7 +2019,6 @@
"src/main/persistence/tracking-repos/repo-update-host-guard.test.ts": 478,
"src/main/persistence/tracking-repos/worktree-identity-migration-field-coverage.test.ts": 505,
"src/main/persistence/window-save-sleep-records.test.ts": 60,
"src/main/pi/managed-extensions/agent-status/agent-status-extension-nested-run-settlement.test.ts": 335,
"src/main/pi/managed-extensions/agent-status/agent-status-extension-session-change.test.ts": 613,
"src/main/pi/managed-extensions/agent-status/agent-status-input-redaction.test.ts": 573,
"src/main/pi/managed-extensions/agent-status/omp-model-command-source.test.ts": 640,
@@ -2279,7 +2263,6 @@
"src/main/runtime/session-graph/graph-sync-deletion-fence.test.ts": 4552,
"src/main/runtime/session-tabs/graph-sync-mobile-snapshot-gating.test.ts": 4333,
"src/main/runtime/terminal/surface/headless-create-terminal-handle-main.test.ts": 3873,
"src/main/runtime/terminal/output/headless-terminal-dispose-write-ordering.test.ts": 4309,
"src/main/runtime/terminal/recovery/held-pane-reopen-layout-owner.test.ts": 5093,
"src/main/runtime/terminal/wait/hermes-slash-readiness-transcript.test.ts": 4931,
"src/main/runtime/terminal/surface/host-pane-remount-terminal-handle.test.ts": 5293,
@@ -2298,7 +2281,6 @@
"src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.test.ts": 701,
"src/main/runtime/mobile-cloud-relay/relay-control-origin.test.ts": 147,
"src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof.test.ts": 122,
"src/main/runtime/mobile-cloud-relay/director/relay-http-client.test.ts": 175,
"src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.test.ts": 73,
"src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts": 804,
"src/main/runtime/mobile-desktop-relay/mobile-desktop-relay.integration.test.ts": 11377,
@@ -2307,7 +2289,6 @@
"src/main/runtime/mobile-desktop-relay/mobile-relay-host-catalog.test.ts": 430,
"src/main/runtime/mobile-desktop-relay/on-demand-server-worktree-rows.test.ts": 383,
"src/main/runtime/mobile-desktop-relay/relayed-phone-frames.test.ts": 1022,
"src/main/runtime/push/notifications/mobile-notification-dismissal-read-failure.test.ts": 181,
"src/main/runtime/push/notifications/mobile-notification-dismissal-store.test.ts": 214,
"src/main/runtime/rpc/server/pairing/mobile-pairing-userdata-path.test.ts": 171,
"src/main/runtime/terminal/layout/mobile-presence-lock.test.ts": 25928,
@@ -2402,12 +2383,10 @@
"src/main/runtime/orchestration/db/schema/dispatch-consumer-generation-migration.test.ts": 640,
"src/main/runtime/orchestration/db/dispatch-context/dispatch-failure-idempotency.test.ts": 544,
"src/main/runtime/orchestration/federation/synchronization/federation-acknowledgment-integrity.test.ts": 557,
"src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts": 566,
"src/main/runtime/orchestration/federation/synchronization/federation-sync.test.ts": 5264,
"src/main/runtime/orchestration/workers/lifecycle/lifecycle-caller-edges.test.ts": 522,
"src/main/runtime/orchestration/workers/lifecycle/lifecycle-reconciliation.test.ts": 884,
"src/main/runtime/orchestration/workers/reports/lightweight-run-worker-exit-escalation.test.ts": 5194,
"src/main/runtime/orchestration/db/messages/mailbox-pointer-release-query.test.ts": 658,
"src/main/runtime/orchestration/mailbox/terminal-pointer/mailbox-pointer-stage.test.ts": 739,
"src/main/runtime/orchestration/mailbox/terminal-pointer/mailbox-pointer-submit.test.ts": 1513,
"src/main/runtime/orchestration/db/messages/message-batch-atomicity.test.ts": 639,
@@ -2576,7 +2555,6 @@
"src/main/runtime/rpc/methods/orchestration/worker/output/worker-output.test.ts": 541,
"src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-authority-contracts.test.ts": 3949,
"src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-evidence-contracts.test.ts": 4491,
"src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-mobile-report.test.ts": 4562,
"src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts": 5889,
"src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts": 4766,
"src/main/runtime/rpc/methods/orchestration/worker/worker-start-budgets.test.ts": 45,
@@ -2622,7 +2600,6 @@
"src/main/runtime/rpc/methods/workspace-layout/workspace-layout-apply.test.ts": 5949,
"src/main/runtime/rpc/methods/workspace-layout/workspace-layout.test.ts": 3391,
"src/main/runtime/rpc/methods/workspaces/worktree-catalog-snapshot-method.test.ts": 1590,
"src/main/runtime/rpc/methods/workspaces/worktree-runtime-routing.test.ts": 1735,
"src/main/runtime/rpc/methods/workspaces/worktree.test.ts": 1645,
"src/main/runtime/rpc/mobile-clipboard-image-provenance.test.ts": 52,
"src/main/runtime/rpc/mobile-e2ee-outbound-memory-budget.test.ts": 61,
@@ -2740,7 +2717,6 @@
"src/main/runtime/workspaces/creation/runtime-provisioned-root-adoption.test.ts": 537,
"src/main/runtime/workspaces/references/runtime-reference-agents.test.ts": 207,
"src/main/runtime/workspaces/references/runtime-reference-find.test.ts": 245,
"src/main/runtime/repositories/runtime-repo-update-worktree-refresh.test.ts": 4375,
"src/main/runtime/repositories/runtime-repository-clone-host-dedupe.test.ts": 874,
"src/main/runtime/repositories/runtime-repository-registration-controller.test.ts": 742,
"src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts": 4402,
@@ -2793,7 +2769,6 @@
"src/main/runtime/sidebar-inputs/workspace-rows/paired-server-rows-producer.test.ts": 340,
"src/main/runtime/sidebar-inputs/repo-icons/repo-icon-data-urls.test.ts": 250,
"src/main/runtime/sidebar-inputs/repo-icon-remote-fetch.test.ts": 101,
"src/main/runtime/sidebar-inputs/sidebar-clock.test.ts": 45,
"src/main/runtime/sidebar-inputs/sidebar-inputs-feed-announcements.test.ts": 1954,
"src/main/runtime/sidebar-inputs/sidebar-inputs-feed-domains.test.ts": 496,
"src/main/runtime/sidebar-inputs/feed/sidebar-inputs-feed-pages.test.ts": 162,
@@ -2805,7 +2780,6 @@
"src/main/runtime/sidebar-inputs/workspace-rows/workspace-rows-producer.test.ts": 4181,
"src/main/runtime/sidebar-inputs/temporal/workspace-viewers.test.ts": 65,
"src/main/runtime/terminal/output/stale-title-display-surfaces.test.ts": 4456,
"src/main/runtime/agent-session/lifecycle/structured-agent-cli-writers.test.ts": 140,
"src/main/runtime/agent-session/lifecycle/structured-agent-session-history-close-race.test.ts": 5020,
"src/main/runtime/agent-session/naming/structured-agent-session-provider-naming-shutdown.test.ts": 1987,
"src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts": 720,
@@ -3039,7 +3013,6 @@
"src/main/star-nag/service-threshold-prompt.test.ts": 307,
"src/main/startup/agent-hooks-uninstall-preflight-real-removers.test.ts": 597,
"src/main/startup/codex-account-restart-resume.test.ts": 465,
"src/main/startup/configure-process-macports-path.test.ts": 159,
"src/main/startup/configure-process.test.ts": 255,
"src/main/startup/e2e-external-open-guard.test.ts": 44,
"src/main/startup/first-window-startup-services.test.ts": 54,
@@ -3114,7 +3087,6 @@
"src/main/updater/mac-install/shipit-leftover-recovery.test.ts": 136,
"src/main/usage/reporting/token-usage/analytics-session-id-store.test.ts": 195,
"src/main/usage/source-input/jsonl/jsonl-file-reader.test.ts": 112,
"src/main/usage/rollups/usage-breakdown-scaling.test.ts": 84,
"src/main/usage/cache/usage-source-cache-file.test.ts": 94,
"src/main/warp-themes/index.test.ts": 678,
"src/main/window/clipboard-agent-session-attachment-paste.test.ts": 585,
@@ -3349,7 +3321,6 @@
"src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx": 4357,
"src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts": 1057,
"src/renderer/src/components/browser-pane/workspace-doc/doc-preview-webview-attach.test.ts": 200,
"src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts": 439,
"src/renderer/src/components/cmd-j/palette-focus-restore-target.test.ts": 186,
"src/renderer/src/components/cmd-j/task-search-activation.test.ts": 1880,
"src/renderer/src/components/confirmation-dialog.test.tsx": 1231,
@@ -3600,7 +3571,6 @@
"src/renderer/src/components/native-chat/session/status/structured-chat-sleep-startup.test.tsx": 2285,
"src/renderer/src/components/native-chat/attachments/chips/use-native-chat-composer-attachments.test.tsx": 2467,
"src/renderer/src/components/native-chat/attachments/intake/use-native-chat-external-attachments.test.tsx": 797,
"src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-live-session-pending.test.ts": 2063,
"src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-live-session-visibility.test.ts": 2047,
"src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-live-session.test.ts": 2218,
"src/renderer/src/components/native-chat/composer/pickers/use-native-chat-mention-files.test.tsx": 2162,
@@ -3633,7 +3603,6 @@
"src/renderer/src/components/pull-request-page/page/use-details.test.tsx": 745,
"src/renderer/src/components/quick-open-file-list-host-name-filter.react.test.tsx": 1941,
"src/renderer/src/components/quick-open-file-list.test.ts": 54,
"src/renderer/src/components/right-sidebar/ai-vault/session-list/AiVaultSessionVirtualList.measurement.test.tsx": 3117,
"src/renderer/src/components/right-sidebar/FolderWorkspaceWorktreesPanel.test.tsx": 461,
"src/renderer/src/components/right-sidebar/plugin-panels/PluginPanel.test.tsx": 2710,
"src/renderer/src/components/right-sidebar/PortsPanel.test.tsx": 1618,
@@ -3703,7 +3672,6 @@
"src/renderer/src/components/sidebar/CommentMarkdown.unknown-html.test.tsx": 3140,
"src/renderer/src/components/sidebar/CommentMarkdown.word-fade.test.tsx": 2113,
"src/renderer/src/components/sidebar/HostRemoveDialog.test.tsx": 6650,
"src/renderer/src/components/sidebar/host-path-browser/RemoteFileBrowser.keyboard.test.tsx": 825,
"src/renderer/src/components/sidebar/Sidebar.test.tsx": 833,
"src/renderer/src/components/sidebar/SidebarAgentsList.test.tsx": 2985,
"src/renderer/src/components/sidebar/workspace-card/surface/WorktreeCard.single-reference-details.test.tsx": 2032,
@@ -3970,7 +3938,6 @@
"src/renderer/src/hooks/ipc-events/agent-status-terminal-title-tab-write.test.ts": 2247,
"src/renderer/src/hooks/ipc-events/browser-request-ipc-bridge.owner.test.ts": 623,
"src/renderer/src/hooks/ipc-events/browser-state-open-link-profile.test.ts": 934,
"src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge-reveal.test.ts": 1764,
"src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.test.ts": 2200,
"src/renderer/src/hooks/ipc-events/quit-and-stop-all-sessions-ipc-bridge.test.ts": 398,
"src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge-ownership.test.ts": 2068,
@@ -4043,7 +4010,6 @@
"src/renderer/src/lib/automation-terminal-ownership.test.ts": 1795,
"src/renderer/src/lib/browser/navigation/browser-link-open.test.ts": 2215,
"src/renderer/src/lib/browser/navigation/browser-link-profile-isolation.test.ts": 2511,
"src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts": 480,
"src/renderer/src/lib/skills/runtime/bundled-skill-target.test.ts": 54,
"src/renderer/src/lib/source-control/checks/check-run-details-log-normalization-performance.test.ts": 846,
"src/renderer/src/lib/source-control/checks/check-run-details-log-normalization.test.ts": 75,
@@ -4059,7 +4025,6 @@
"src/renderer/src/lib/agent-session/launch/background/launch-agent-background-session-launch-parity.test.ts": 2792,
"src/renderer/src/lib/agent-session/launch/background/launch-agent-background-session.test.ts": 1040,
"src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-new-tab-host-route-readiness.test.ts": 489,
"src/renderer/src/lib/agent-session/launch/continuation/launch-agent-session-continuation-toast.test.tsx": 2347,
"src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-defaults.test.ts": 1594,
"src/renderer/src/lib/work-items/linear/linear-issue-workspace-attachment.test.ts": 99,
"src/renderer/src/lib/work-items/linked-work-item-context.test.ts": 64,
@@ -4112,7 +4077,6 @@
"src/renderer/src/lib/workspace/activation/worktree-reactivation-preserved-pane-replacement.test.ts": 2268,
"src/renderer/src/lib/workspace/activation/worktree-reactivation-tab-forkbomb.test.ts": 4131,
"src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts": 380,
"src/renderer/src/lib/workspace/persistence/wsl-move-renderer-store-rewrites.test.ts": 1072,
"src/renderer/src/runtime/rpc/calls/abortable-runtime-environment-call.test.ts": 189,
"src/renderer/src/runtime/web-session-tabs-sync/closing/close-mirrored-editor-tab.test.ts": 397,
"src/renderer/src/runtime/files/mutations/file-explorer-delete-owner-provenance.test.ts": 1878,
@@ -4154,7 +4118,6 @@
"src/renderer/src/runtime/web-session-tabs-sync/subscriptions/web-session-tabs-sync-visibility-collision.test.tsx": 2699,
"src/renderer/src/runtime/web-session-tabs-sync/subscriptions/web-session-tabs-sync-window-visibility.test.tsx": 2589,
"src/renderer/src/runtime/web-session-tabs-sync/subscriptions/web-session-tabs-sync-worktree-switch.test.tsx": 2625,
"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync.test.ts": 1006,
"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts": 923,
"src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts": 723,
"src/renderer/src/runtime/hosted-terminals/recovery/evidence/web-session-terminal-retirement-proof-ledger.test.ts": 685,
@@ -4180,7 +4143,6 @@
"src/renderer/src/store/slices/agent-status/agent-status-row-order-origin.test.ts": 2205,
"src/renderer/src/store/slices/agent-status/agent-status-ssh-connection-clear.test.ts": 1681,
"src/renderer/src/store/slices/agent-status/agent-status.test.ts": 2129,
"src/renderer/src/store/repos/all-host-catalog-settlement.test.ts": 1955,
"src/renderer/src/store/slices/browser/annotations/browser-annotation-retention.test.ts": 8178,
"src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts": 1777,
"src/renderer/src/store/slices/browser/hosts/browser-session-host-selection.test.ts": 988,
@@ -4232,7 +4194,6 @@
"src/renderer/src/store/slices/runtime-status/set-runtime-environments-purge-wiring.test.ts": 1683,
"src/renderer/src/store/slices/settings/settings-terminal-quick-commands.test.ts": 1734,
"src/renderer/src/store/terminals/store-create-tab-start-in-main.test.ts": 1801,
"src/renderer/src/store/slices/tabs/store-open-to-side-layout-owner.test.ts": 1919,
"src/renderer/src/store/terminals/store-sleep-exact-runtime-stop.test.ts": 1842,
"src/renderer/src/store/terminals/store-sleep-pane-hibernation.test.ts": 1932,
"src/renderer/src/store/slices/tabs/tabs-close-dangling-group.test.ts": 1849,
@@ -4253,7 +4214,6 @@
"src/renderer/src/store/slices/worktrees/teardown/worktrees-always-force-delete.test.ts": 1611,
"src/renderer/src/store/slices/worktrees/create/worktrees-create-captured-host.test.ts": 1148,
"src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-refresh-coalescing.test.ts": 1226,
"src/renderer/src/store/slices/worktrees/metadata/worktrees-fetch-remote-lineage.test.ts": 1221,
"src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-removal-purge.test.ts": 1207,
"src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-stale-catalog-version.test.ts": 1337,
"src/renderer/src/store/slices/worktrees/metadata/worktrees-git-identity-branch-title.test.ts": 1181,
@@ -4410,7 +4370,6 @@
"src/shared/claude-agent-view-launch.test.ts": 55,
"src/shared/claude-background-run-isolation.test.ts": 43,
"src/shared/agent-hook-listener/normalization/claude-background-task-status.test.ts": 315,
"src/shared/claude-shell-function.test.ts": 220,
"src/shared/cloud-service-url.test.ts": 37,
"src/shared/coalescing-keyed-runner.test.ts": 119,
"src/shared/codebuddy-agent.test.ts": 301,
@@ -4557,7 +4516,6 @@
"src/shared/node-bounded-file-reader-sync.test.ts": 56,
"src/shared/node-bounded-file-reader-window.test.ts": 63,
"src/shared/node-bounded-file-reader.test.ts": 67,
"src/shared/node-cli-command-async-resolution.test.ts": 77,
"src/shared/node-readable-text.test.ts": 45,
"src/shared/node-source-copy-content-equality.test.ts": 52,
"src/shared/nvm-default-alias.test.ts": 81,
@@ -4723,7 +4681,6 @@
"src/shared/sidebar-list/sidebar-inputs-feed-installer.test.ts": 100,
"src/shared/sidebar-list/smart-sort.test.ts": 131,
"src/shared/sleeping-record-legacy-pane-key.test.ts": 59,
"src/shared/source-control/listing/source-control-discard-all-sequence.test.ts": 50,
"src/shared/source-scan/source-tree-scan.test.ts": 50,
"src/shared/source-scan/source-tree-walk.test.ts": 62,
"src/shared/ssh-pty-id.test.ts": 51,
@@ -4781,7 +4738,6 @@
"src/shared/windows-command-line-budget.test.ts": 105,
"src/shared/windows-interactive-login-spawn.test.ts": 54,
"src/shared/windows-private-credential-file.test.ts": 77,
"src/shared/windows-secure-dacl.test.ts": 65,
"src/shared/windows-security-addon.win32.test.ts": 73,
"src/shared/windows-transient-lock-removal.test.ts": 198,
"src/shared/worker-auto-close.test.ts": 60,
@@ -4823,7 +4779,6 @@
"src/shared/workspace-layout/editor-tabs/workspace-layout-workspace-move.test.ts": 181,
"src/shared/workspace-attachments/workspace-linked-item-source-context.test.ts": 65,
"src/shared/workspace-attachments/workspace-reference-identity.test.ts": 82,
"src/shared/workspace-review-checks.test.ts": 82,
"src/shared/workspace-session/workspace-session-salvage.test.ts": 930,
"src/shared/workspace-session/workspace-session-schema.sleeping-agent.test.ts": 337,
"src/shared/workspace-session/workspace-session-terminal-buffers.test.ts": 294,
@@ -43,7 +43,6 @@ export const UNIT_EXCLUDE = [
'src/shared/shell/wsl/fish-wsl-cwd-report.node-pty.test.ts',
'src/main/wsl/filesystem/wsl-sh-cwd-report.node-pty.test.ts',
'src/shared/terminal/pty/ingress/pty-reply-echo-shapes.node-pty.test.ts',
'src/shared/shell/launch/startup-shell-portability.live-shell.test.ts',
'src/shared/shell/command-resolution/posix-command-path-lookup.test.ts',
'tests/e2e/relay-region-correction.unit.test.ts',
'src/main/browser/cookies/browser-google-cookie-clear.electron.test.ts',
@@ -1,148 +0,0 @@
// An HTML file opened on the file-preview route must paint as a page, not as its source text (iOS P0).
// Full bundle, real route, shipped CSP and document headers; WebKit stands in for WKWebView.
import { mkdir, mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { chromium, webkit } from 'playwright-core'
import { buildMobileWebAppBundle } from '../../build/mobile-web-app/build-mobile-web-app-bundle.mjs'
import { mobileWebAppDependenciesPresent } from '../mobile-web-app-bundle-dependencies.mjs'
import {
createBundleServer,
installShellDouble,
readBridgeFaultGrant,
readBridgeProtocolVersion,
readShellCsp,
readShellDocumentHeaders
} from './mobile-web-app-render-harness.mjs'
import { probePreviewPixel } from './mobile-web-app-preview-frame-readings.mjs'
import { MOBILE_WEB_PAGE_ROUTES } from '../../build/mobile-web-app/mobile-web-page-routes.mjs'
const MARKER = 'ORCA_HTML_FILE_RENDERED'
const PAINT_RGB = '0,128,255'
const HTML = `<!doctype html>
<html>
<body style="margin:0;min-height:100vh;background:rgb(${PAINT_RGB})">
<h1>${MARKER}</h1>
</body>
</html>`
const host = { id: 'html-host', name: 'HTML Host', endpoint: 'ws://html-test', lastConnected: 1 }
const pattern = '/h/[hostId]/files/preview/[worktreeId]'
const pathname = '/h/html-host/files/preview/folder-project'
const bundles = mobileWebAppDependenciesPresent()
const shots = process.env.ORCA_MOBILE_HTML_FILE_SHOTS_DIR
const browsers = {}
let scratch, server, origin, version, faultGrant
beforeAll(async () => {
if (!bundles) {
return
}
scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-html-file-render-'))
const built = await buildMobileWebAppBundle({ outDir: join(scratch, 'bundle') })
const policy = await readShellCsp()
const documentHeaders = await readShellDocumentHeaders()
version = await readBridgeProtocolVersion()
faultGrant = await readBridgeFaultGrant()
const served = await createBundleServer({
outDir: built.outDir,
cspHeader: policy,
documentHeaders
})
server = served.server
origin = served.origin
const executablePath = process.env.ORCA_MOBILE_WEB_RENDER_BROWSER
browsers.chromium = await chromium.launch({
headless: true,
...(executablePath ? { executablePath } : {})
})
browsers.webkit = await webkit.launch({ headless: true })
if (shots) {
await mkdir(shots, { recursive: true })
}
}, 240_000)
afterAll(async () => {
await browsers.chromium?.close()
await browsers.webkit?.close()
await new Promise((resolve) => (server ? server.close(resolve) : resolve()))
if (scratch) {
await rm(scratch, { recursive: true, force: true })
}
})
async function openHtmlFile(browser, { line, truncated = false, editable = false } = {}) {
const context = await browser.newContext({
viewport: { width: 390, height: 844 },
hasTouch: true
})
const page = await context.newPage()
const errors = []
page.on('pageerror', (error) => errors.push(error.message))
const route = MOBILE_WEB_PAGE_ROUTES.find((entry) => entry.pathname === pattern)
await page.addInitScript(installShellDouble, {
version,
sessionId: 'html-session',
buildId: 'html-build',
route: {
pathname,
params: {
relativePath: 'index.html',
name: 'index.html',
worktreeName: 'Folder project',
...(line ? { line } : {}),
...(editable
? { source: 'terminalArtifact', absolutePath: '/tmp/index.html', grantId: 'html-grant' }
: {})
}
},
host,
storage: {},
faultGrant,
grants: [faultGrant, ...route.grants, ...(route.optionalGrants ?? [])],
pageRoutes: [pattern],
replies: {
[editable ? 'files.readTerminalArtifact' : 'files.read']: {
content: HTML,
byteLength: HTML.length,
truncated
}
}
})
await page.goto(`${origin}/`)
return { context, page, errors }
}
/** Pixel near the frame's bottom: engines refuse DOM reads inside the opaque frame, but not screenshots. */
async function framePixel(page) {
const box = await page.locator('iframe').boundingBox()
return await probePreviewPixel(page, {
x: box.x + box.width / 2,
y: box.y + box.height - 40,
width: 4,
height: 4
})
}
for (const engine of ['chromium', 'webkit']) {
const describeRender = bundles ? describe : describe.skip
describeRender(`an HTML file on the file-preview route on ${engine}`, () => {
it('renders unsaved HTML edits and retains them when returning to Source', async () => {
const { context, page, errors } = await openHtmlFile(browsers[engine], { editable: true })
await page.locator('iframe').waitFor({ timeout: 60_000 })
await page.getByRole('tab', { name: 'View HTML source' }).click()
const editor = page.getByRole('textbox', { name: 'index.html editor' })
await editor.fill(
'<body style="margin:0;min-height:100vh;background:rgb(255,0,128)">Draft</body>'
)
await page.getByRole('tab', { name: 'Preview rendered HTML' }).click()
await expect.poll(() => framePixel(page), { timeout: 10_000 }).toBe('255,0,128')
await page.getByRole('tab', { name: 'View HTML source' }).click()
expect(await editor.inputValue()).toBe(
'<body style="margin:0;min-height:100vh;background:rgb(255,0,128)">Draft</body>'
)
expect(errors).toEqual([])
await context.close()
}, 90_000)
})
}
@@ -1,157 +0,0 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { chromium } from 'playwright-core'
import { buildMobileWebAppBundle } from '../../build/mobile-web-app/build-mobile-web-app-bundle.mjs'
import { mobileWebAppDependenciesPresent } from '../mobile-web-app-bundle-dependencies.mjs'
import {
createBundleServer,
installShellDouble,
readBridgeFaultGrant,
readBridgeProtocolVersion,
readShellCsp
} from './mobile-web-app-render-harness.mjs'
import { MOBILE_WEB_PAGE_ROUTES } from '../../build/mobile-web-app/mobile-web-page-routes.mjs'
// Two gray VP9 frames generated with ffmpeg, without audio or user content.
const WEBM =
'GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAH6EU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHWTbuMU6uEElTDZ1OsggEjTbuMU6uEHFO7a1OsggHk7AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmsCrXsYMPQkBNgIxMYXZmNjIuMy4xMDBXQYxMYXZmNjIuMy4xMDBEiYhAn0AAAAAAABZUrmvIrgEAAAAAAAA/14EBc8WIPYwl7RGcI1acgQAitZyDdW5kiIEAhoVWX1ZQOYOBASPjg4Q7msoA4JCwgSC6gSCagQJVsIRVuYEBElTDZ0B/c3OfY8CAZ8iZRaOHRU5DT0RFUkSHjExhdmY2Mi4zLjEwMHNz2mPAi2PFiD2MJe0RnCNWZ8ilRaOHRU5DT0RFUkSHmExhdmM2Mi4xMS4xMDAgbGlidnB4LXZwOWfIoUWjiERVUkFUSU9ORIeTMDA6MDA6MDIuMDAwMDAwMDAwAB9DtnW354EAo52BAACAgkmDQgAB8AH2ADgkHBhKAAAwYAAAItXAAKOTgQPoAIYAQJKcAFAAAANgAABDQBxTu2uRu4+zgQC3iveBAfGCAajwgQM='
function wavFixture() {
const bytes = Buffer.alloc(44 + 8000 * 2 * 2)
bytes.write('RIFF')
bytes.writeUInt32LE(bytes.length - 8, 4)
bytes.write('WAVEfmt ', 8)
bytes.writeUInt32LE(16, 16)
bytes.writeUInt16LE(1, 20)
bytes.writeUInt16LE(1, 22)
bytes.writeUInt32LE(8000, 24)
bytes.writeUInt32LE(16000, 28)
bytes.writeUInt16LE(2, 32)
bytes.writeUInt16LE(16, 34)
bytes.write('data', 36)
bytes.writeUInt32LE(bytes.length - 44, 40)
return bytes
}
const host = { id: 'media-host', name: 'Media Host', endpoint: 'ws://media-test', lastConnected: 1 }
const pattern = '/h/[hostId]/files/preview/[worktreeId]'
const pathname = '/h/media-host/files/preview/folder-project'
const bundles = mobileWebAppDependenciesPresent()
let scratch, server, origin, browser, policy, version, faultGrant
beforeAll(async () => {
if (!bundles) {
return
}
scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-media-render-'))
const built = await buildMobileWebAppBundle({ outDir: join(scratch, 'bundle') })
policy = await readShellCsp()
version = await readBridgeProtocolVersion()
faultGrant = await readBridgeFaultGrant()
const served = await createBundleServer({
outDir: built.outDir,
cspHeader: policy
})
server = served.server
origin = served.origin
const executablePath = process.env.ORCA_MOBILE_WEB_RENDER_BROWSER
browser = await chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}) })
}, 120_000)
afterAll(async () => {
await browser?.close()
await new Promise((resolve) => (server ? server.close(resolve) : resolve()))
if (scratch) {
await rm(scratch, { recursive: true, force: true })
}
})
async function openMedia(relativePath, bytes) {
const page = await browser.newPage({ viewport: { width: 390, height: 844 } })
const errors = []
page.on('pageerror', (error) => errors.push(error.message))
const grants = MOBILE_WEB_PAGE_ROUTES.find((route) => route.pathname === pattern).grants
await page.addInitScript(installShellDouble, {
version,
sessionId: 'media-session',
buildId: 'media-build',
route: {
pathname,
params: { relativePath, name: relativePath, worktreeName: 'Folder project' }
},
host,
storage: {},
faultGrant,
grants: [faultGrant, ...grants],
pageRoutes: [pattern],
replies: {
'files.stat': { size: bytes.length, isDirectory: false, mtime: 1 },
'files.readChunk': {
contentBase64: bytes.toString('base64'),
bytesRead: bytes.length,
eof: true
},
'files.read': {
content: 'Playback stopped after switching files',
byteLength: 43,
truncated: false
}
}
})
await page.addInitScript(() => {
globalThis.__revokedMedia = []
const revoke = URL.revokeObjectURL.bind(URL)
URL.revokeObjectURL = (uri) => {
globalThis.__revokedMedia.push(uri)
revoke(uri)
}
})
await page.goto(`${origin}/`)
return { page, errors }
}
const describeRender = bundles ? describe : describe.skip
describeRender('mobile media under the shipped shell policy', () => {
it.each([
['music.wav', wavFixture(), 'audio'],
['movie.webm', Buffer.from(WEBM, 'base64'), 'video']
])(
'plays and seeks %s, then releases playback and its Blob on navigation',
async (name, bytes, tag) => {
const { page, errors } = await openMedia(name, bytes)
await page.waitForFunction((tag) => document.querySelector(tag)?.readyState >= 2, tag)
await page.evaluate(async (tag) => {
const media = document.querySelector(tag)
globalThis.__previousMedia = media
media.muted = true
media.currentTime = 1
await media.play()
}, tag)
await page.waitForFunction((tag) => document.querySelector(tag).currentTime > 1, tag, {
timeout: 10_000
})
const playback = await page.evaluate((tag) => {
const media = document.querySelector(tag)
media.pause()
return {
duration: media.duration,
time: media.currentTime,
uri: media.currentSrc
}
}, tag)
expect(playback.duration).toBeCloseTo(2, 1)
expect(playback.time).toBeGreaterThan(1)
await page.evaluate((pathname) => {
history.pushState(null, '', `${pathname}?relativePath=README.md`)
dispatchEvent(new PopStateEvent('popstate'))
}, pathname)
await page.getByText('Playback stopped after switching files', { exact: true }).waitFor()
expect(
await page.evaluate(() => ({
paused: globalThis.__previousMedia.paused,
src: globalThis.__previousMedia.getAttribute('src'),
revoked: globalThis.__revokedMedia
}))
).toEqual({ paused: true, src: null, revoked: [playback.uri] })
expect(errors).toEqual([])
await page.close()
},
60_000
)
})
@@ -1,139 +0,0 @@
import { mkdir, mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { chromium } from 'playwright-core'
import { buildMobileWebAppBundle } from '../../build/mobile-web-app/build-mobile-web-app-bundle.mjs'
import { mobileWebAppDependenciesPresent } from '../mobile-web-app-bundle-dependencies.mjs'
import {
createBundleServer,
installShellDouble,
readBridgeFaultGrant,
readBridgeProtocolVersion,
readShellCsp
} from './mobile-web-app-render-harness.mjs'
import { MOBILE_WEB_PAGE_ROUTES } from '../../build/mobile-web-app/mobile-web-page-routes.mjs'
// viewBox only: browsers size this 300 x 60 unless the viewer reads the drawing's own extent.
const SVG =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 240"><rect width="1200" height="240" fill="#2563eb"/><circle cx="600" cy="120" r="80" fill="#facc15"/></svg>'
const host = { id: 'svg-host', name: 'SVG Host', endpoint: 'ws://svg-test', lastConnected: 1 }
const pattern = '/h/[hostId]/files/preview/[worktreeId]'
const pathname = '/h/svg-host/files/preview/folder-project'
const bundles = mobileWebAppDependenciesPresent()
const shots = process.env.ORCA_MOBILE_SVG_SHOTS_DIR
let scratch, server, origin, browser, policy, version, faultGrant
beforeAll(async () => {
if (!bundles) {
return
}
scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-svg-render-'))
const built = await buildMobileWebAppBundle({ outDir: join(scratch, 'bundle') })
policy = await readShellCsp()
version = await readBridgeProtocolVersion()
faultGrant = await readBridgeFaultGrant()
const served = await createBundleServer({ outDir: built.outDir, cspHeader: () => policy })
server = served.server
origin = served.origin
const executablePath = process.env.ORCA_MOBILE_WEB_RENDER_BROWSER
browser = await chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}) })
if (shots) {
await mkdir(shots, { recursive: true })
}
}, 120_000)
afterAll(async () => {
await browser?.close()
await new Promise((resolve) => (server ? server.close(resolve) : resolve()))
if (scratch) {
await rm(scratch, { recursive: true, force: true })
}
})
async function openSvg() {
const context = await browser.newContext({
viewport: { width: 390, height: 844 },
hasTouch: true
})
const page = await context.newPage()
const errors = []
page.on('pageerror', (error) => errors.push(error.message))
const grants = MOBILE_WEB_PAGE_ROUTES.find((route) => route.pathname === pattern).grants
await page.addInitScript(installShellDouble, {
version,
sessionId: 'svg-session',
buildId: 'svg-build',
route: {
pathname,
params: { relativePath: 'logo.svg', name: 'logo.svg', worktreeName: 'Folder project' }
},
host,
storage: {},
faultGrant,
grants: [faultGrant, ...grants],
pageRoutes: [pattern],
replies: { 'files.read': { content: SVG, byteLength: SVG.length, truncated: false } }
})
await page.goto(`${origin}/`)
return { context, page, errors }
}
function drawing(page) {
return page.getByRole('img', { name: 'logo.svg drawing' })
}
async function touch(cdp, type, points) {
await cdp.send('Input.dispatchTouchEvent', {
type,
touchPoints: points.map(([x, y], id) => ({ x, y, id }))
})
}
const describeRender = bundles ? describe : describe.skip
describeRender('mobile SVG preview under the shipped shell policy', () => {
it('draws the SVG at its own aspect, pinches and double-taps to zoom, and keeps source', async () => {
const { context, page, errors } = await openSvg()
const img = drawing(page)
await page.waitForFunction(
() => document.querySelector('img[alt="logo.svg drawing"]')?.complete
)
const fitted = await img.boundingBox()
// Fit fills the phone's width, so the 5:1 drawing is upscaled past the browser's 300 px guess.
expect(fitted.width).toBeGreaterThan(330)
expect(fitted.width / fitted.height).toBeCloseTo(5, 1)
expect(
await img.evaluate((element) => element.naturalWidth > 0 && element.naturalHeight > 0)
).toBe(true)
if (shots) {
await page.screenshot({ path: join(shots, 'mobile-svg-fit.png') })
}
const cdp = await context.newCDPSession(page)
const y = fitted.y + fitted.height / 2
const x = fitted.x + fitted.width / 2
await touch(cdp, 'touchStart', [
[x - 40, y],
[x + 40, y]
])
for (let step = 1; step <= 5; step++) {
await touch(cdp, 'touchMove', [
[x - 40 - step * 20, y],
[x + 40 + step * 20, y]
])
}
await touch(cdp, 'touchEnd', [])
const pinched = await img.boundingBox()
expect(pinched.width).toBeGreaterThan(fitted.width * 2)
if (shots) {
await page.screenshot({ path: join(shots, 'mobile-svg-pinched.png') })
}
await page.touchscreen.tap(x, y)
await page.touchscreen.tap(x, y)
await expect.poll(async () => (await img.boundingBox()).width).toBeCloseTo(fitted.width, 0)
await page.getByRole('tab', { name: 'View SVG source' }).click()
await page.getByText('viewBox="0 0 1200 240"', { exact: false }).waitFor()
expect(errors).toEqual([])
await context.close()
}, 60_000)
})
@@ -1,175 +0,0 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { chromium } from 'playwright-core'
import { buildMobileWebAppBundle } from '../../build/mobile-web-app/build-mobile-web-app-bundle.mjs'
import { mobileWebAppDependenciesPresent } from '../mobile-web-app-bundle-dependencies.mjs'
import { MOBILE_WEB_PAGE_ROUTES } from '../../build/mobile-web-app/mobile-web-page-routes.mjs'
import {
createBundleServer,
installShellDouble,
readBridgeFaultGrant,
readBridgeProtocolVersion,
readShellCsp,
waitForRecordedRequests,
waitForPageFrames
} from '../preview/mobile-web-app-render-harness.mjs'
const HOST_ROUTE = '/h/render-check-host'
const WORKTREE = 'wt-1'
const SESSION_ROUTE = `${HOST_ROUTE}/session/${WORKTREE}`
const SESSION_PATTERN = '/h/[hostId]/session/[worktreeId]'
const PAGE_ROUTE_PATTERNS = ['/h/[hostId]', SESSION_PATTERN]
const SHELL_SESSION_ID = 'session-render-session'
const SHELL_BUILD_ID = 'session-render-build'
const SHELL_HOST = {
id: 'render-check-host',
name: 'Render Check Host',
endpoint: 'ws://render-check',
lastConnected: 1
}
// Read grants from manifest so new route grants are exercised instead of silently omitted by copied fixture.
function sessionGrants() {
const declared = MOBILE_WEB_PAGE_ROUTES.find((route) => route.pathname === SESSION_PATTERN)
if (!declared) {
throw new Error(`${SESSION_PATTERN} is not registered`)
}
return declared.grants
}
const bundles = mobileWebAppDependenciesPresent()
const describeRender = bundles ? describe : describe.skip
let scratch
let server
let browser
let origin
let cspHeader = null
let bridgeVersion = null
let faultGrant = null
beforeAll(async () => {
if (!bundles) {
return
}
cspHeader = await readShellCsp()
bridgeVersion = await readBridgeProtocolVersion()
faultGrant = await readBridgeFaultGrant()
scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-web-app-session-'))
const built = await buildMobileWebAppBundle({ outDir: join(scratch, 'bundle') })
const served = await createBundleServer({ outDir: built.outDir, cspHeader })
server = served.server
origin = served.origin
const executablePath = process.env.ORCA_MOBILE_WEB_RENDER_BROWSER
browser = await chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}) })
}, 240_000)
afterAll(async () => {
await browser?.close()
server?.close()
if (scratch) {
await rm(scratch, { recursive: true, force: true })
}
})
async function openPage(route, replies = {}, { domStorageOff = false } = {}) {
const page = await browser.newPage({ viewport: { width: 390, height: 844 } })
if (domStorageOff) {
// Match Android WebView storage-off behavior: localStorage is null, not undefined; import-time push storage reads once threw getItem here.
await page.addInitScript(() => {
Object.defineProperty(window, 'localStorage', { configurable: true, get: () => null })
})
}
// Install channel at document start like native shell; entry reads it before load.
await page.addInitScript(installShellDouble, {
version: bridgeVersion,
sessionId: SHELL_SESSION_ID,
buildId: SHELL_BUILD_ID,
route: { pathname: route },
host: SHELL_HOST,
storage: {},
faultGrant,
grants: [faultGrant, ...sessionGrants()],
pageRoutes: PAGE_ROUTE_PATTERNS,
replies
})
const errors = []
const warnings = []
page.on('pageerror', (error) => errors.push(`${error.name}: ${error.message}`))
page.on('console', (message) => {
if (message.type() === 'error') {
errors.push(`console.error: ${message.text()}`)
}
// Track warnings separately: storage-write-dropped would evade error-only assertions.
if (message.type() === 'warning') {
warnings.push(message.text())
}
})
return { page, errors, warnings }
}
// Wait for route content after mounted: deferred screen chunk may still be arriving.
async function waitForRoute({ page, errors }, route, awaitText) {
const named = (what) =>
new Error(`${route} ${what}: ${errors.join(' | ') || 'no page or console error'}`)
try {
await page.waitForFunction(() => document.documentElement.dataset.orcaWebEntry === 'mounted', {
timeout: 60_000,
polling: 250
})
} catch {
throw named('never mounted')
}
try {
await page.waitForFunction((needle) => document.body.innerText.includes(needle), awaitText, {
timeout: 60_000,
polling: 250
})
} catch {
throw named(`mounted but never painted ${JSON.stringify(awaitText)}`)
}
// Report boundary-caught route fault directly instead of timing out on mount.
for (const fault of await page.evaluate(() => globalThis.__orcaRenderCheckFaults ?? [])) {
errors.push(`page fault: ${fault}`)
}
}
async function openRoute(route, awaitText, replies = {}, options = {}) {
const opened = await openPage(route, replies, options)
await opened.page.goto(`${origin}/`, { waitUntil: 'load' })
await waitForRoute(opened, route, awaitText)
return opened
}
describeRender(
'the session route in a real browser',
() => {
it('paints with DOM storage off, which is how the Android shell serves it', async () => {
// Null-storage arm reproduces Android import-time expo-notifications failure; shell owns push and pages must not load it.
const opened = await openRoute(SESSION_ROUTE, 'Terminal', {}, { domStorageOff: true })
// Require all errors absent; filtering known push failure could hide other illegal storage users.
expect(opened.errors).toEqual([])
await opened.page.close()
}, 120_000)
it('writes no storage key it was never handed, on a mount that read the host status', async () => {
// Answer status.get: host-status-gates once wrote unlisted orca:host-app-version key only after readable reply, invisible to no-RPC cases.
const opened = await openRoute(SESSION_ROUTE, 'Terminal', {
'status.get': {
protocolVersion: 9,
minCompatibleMobileVersion: 1,
appVersion: '1.4.191',
capabilities: []
}
})
await waitForRecordedRequests(opened.page, ['status.get'])
await waitForPageFrames(opened.page)
// Reject every dropped storage write, not just known key, to catch future unlisted writers.
expect(opened.warnings.filter((text) => text.includes('storage-write-dropped'))).toEqual([])
await opened.page.close()
}, 120_000)
},
600_000
)
@@ -1,188 +0,0 @@
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import * as esbuild from 'esbuild'
import { chromium, webkit } from 'playwright-core'
import {
MOBILE_WEB_APP_NATIVE_PARITY_STYLE,
MOBILE_WEB_APP_ROOT_RESET,
mobileWebAppBuildOptions
} from '../../build/mobile-web-app/build-mobile-web-app-bundle.mjs'
import { mobileWebAppDependenciesPresent } from '../mobile-web-app-bundle-dependencies.mjs'
import { createBundleServer, readShellCsp } from '../preview/mobile-web-app-render-harness.mjs'
const mobileDir = fileURLToPath(new URL('../../../../mobile', import.meta.url))
const engines = [
{
name: 'chromium',
launch: () => {
const executablePath = process.env.ORCA_MOBILE_WEB_RENDER_BROWSER
return chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}) })
}
},
{ name: 'webkit', launch: () => webkit.launch({ headless: true }) }
]
const entry = `
import { useState } from 'react'
import { createRoot } from 'react-dom/client'
import { View } from 'react-native'
import { MobileNativeChatComposerField } from './src/session/native-chat/composer/field/MobileNativeChatComposerField.web'
import { publishShellKeyboardSource } from './src/platform/keyboard/keyboard-occlusion'
let keyboardHeight = 0
const listeners = new Set()
if (location.hash !== '#browser') {
publishShellKeyboardSource({
read: () => keyboardHeight,
subscribe: (listener) => {
listeners.add(listener)
return () => listeners.delete(listener)
}
})
}
window.setShellKeyboard = (height) => {
keyboardHeight = height
listeners.forEach((listener) => listener(height))
}
function Composer() {
const [state, setState] = useState({ value: '', placeholder: 'Message', dictationPreview: null })
window.updateComposer = (patch) => setState((previous) => ({ ...previous, ...patch }))
return <View style={{ flex: 1, padding: 12 }}>
<MobileNativeChatComposerField
{...state}
skillToken={null}
multiline
scrollEnabled
accessibilityLabel="Message"
onChangeText={(value) => setState((previous) => ({ ...previous, value }))}
/>
</View>
}
createRoot(document.getElementById('root')).render(<Composer />)
`
const bundles = mobileWebAppDependenciesPresent()
const describeSizing = bundles ? describe : describe.skip
const browsers = new Map()
let scratch
let server
let origin
beforeAll(async () => {
if (!bundles) {
return
}
await mkdir(join(mobileDir, '.tmp'), { recursive: true })
scratch = await mkdtemp(join(mobileDir, '.tmp', 'composer-sizing-'))
const outDir = join(scratch, 'bundle')
await esbuild.build({
...mobileWebAppBuildOptions([]),
entryPoints: undefined,
stdin: { contents: entry, resolveDir: mobileDir, loader: 'tsx', sourcefile: 'composer.tsx' },
splitting: false,
write: true,
outdir: outDir,
entryNames: 'composer',
metafile: false
})
await writeFile(
join(outDir, 'index.html'),
`<!doctype html><html><head><meta charset="utf-8">${MOBILE_WEB_APP_ROOT_RESET}` +
`${MOBILE_WEB_APP_NATIVE_PARITY_STYLE}</head><body><div id="root"></div>` +
'<script type="module" src="/composer.js"></script></body></html>'
)
const served = await createBundleServer({ outDir, cspHeader: await readShellCsp() })
server = served.server
origin = served.origin
for (const engine of engines) {
browsers.set(engine.name, await engine.launch())
}
}, 180_000)
afterAll(async () => {
for (const browser of browsers.values()) {
await browser.close()
}
server?.close()
if (scratch) {
await rm(scratch, { recursive: true, force: true })
}
})
async function openPage(engine, mode = 'shell') {
const page = await browsers.get(engine.name).newPage({ viewport: { width: 390, height: 844 } })
if (mode === 'browser') {
// Model iOS's shrinking visual viewport; RN Web and our keyboard subscription read it independently.
await page.addInitScript(() => {
let keyboard = 0
const viewport = window.visualViewport
Object.defineProperty(viewport, 'height', { get: () => window.innerHeight - keyboard })
window.setVisualKeyboard = (height) => {
keyboard = height
viewport.dispatchEvent(new Event('resize'))
}
})
}
await page.goto(`${origin}/#${mode}`, { waitUntil: 'load' })
const field = page.getByRole('textbox', { name: 'Message' })
await field.waitFor({ state: 'visible' })
return { page, field }
}
function height(field) {
return field.evaluate((input) => input.getBoundingClientRect().height)
}
describeSizing.each(engines)('web composer sizing in $name', (engine) => {
it('grows for newlines and wrapping, remeasures width, and shrinks without losing focus', async () => {
const { page, field } = await openPage(engine)
try {
await field.fill('Short draft')
const compact = await height(field)
await field.fill('First line\nSecond line\nThird line')
await expect.poll(() => height(field)).toBeGreaterThan(compact)
expect(await field.evaluate((input) => input.scrollHeight <= input.clientHeight)).toBe(true)
await field.fill('Review the mobile composer and keep all draft text visible. '.repeat(4))
await expect.poll(() => height(field)).toBeGreaterThan(compact * 2)
const narrow = await height(field)
await page.setViewportSize({ width: 844, height: 844 })
await expect.poll(() => height(field)).toBeLessThan(narrow)
await expect
.poll(() => field.evaluate((input) => input.scrollHeight - input.clientHeight))
.toBeLessThanOrEqual(1)
expect(await field.evaluate((input) => document.activeElement === input)).toBe(true)
await field.fill('Short draft')
await expect.poll(() => height(field)).toBe(compact)
} finally {
await page.close()
}
})
it('grows for dictation without changing the draft or remounting the focused field', async () => {
const { page, field } = await openPage(engine)
try {
await field.fill('Existing draft')
const compact = await height(field)
await page.evaluate(() =>
window.updateComposer({
dictationPreview: {
before: 'Existing draft ',
text: 'Heard words '.repeat(12),
after: ''
}
})
)
await expect.poll(() => height(field)).toBeGreaterThan(compact)
expect(await field.inputValue()).toBe('Existing draft')
expect(await field.evaluate((input) => document.activeElement === input)).toBe(true)
await page.evaluate(() => window.updateComposer({ dictationPreview: null }))
await expect.poll(() => height(field)).toBe(compact)
} finally {
await page.close()
}
})
})
@@ -1,163 +0,0 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { chromium, webkit } from 'playwright-core'
import { buildMobileWebAppBundle } from '../../build/mobile-web-app/build-mobile-web-app-bundle.mjs'
import { mobileWebAppDependenciesPresent } from '../mobile-web-app-bundle-dependencies.mjs'
import {
createBundleServer,
installShellDouble,
readBridgeBackNames,
readBridgeFaultGrant,
readBridgeProtocolVersion,
readShellCsp
} from '../preview/mobile-web-app-render-harness.mjs'
const HOST_ROUTE = '/h/render-check-host'
const SHELL_HOST = {
id: 'render-check-host',
name: 'Render Check Host',
endpoint: 'ws://render-check',
lastConnected: 1
}
const VIEWPORT = { width: 390, height: 844 }
// Without a dependency array, esbuild’s untransformed useAnimatedStyle has no Babel-written __closure, so Reanimated mapper runs only once.
// Both Chromium/WebKit must move; one-engine coverage could falsely support an engine-specific explanation.
const ENGINES = [
{
name: 'chromium',
// Use runner Chrome override to avoid CI browser downloads.
launch: () => {
const executablePath = process.env.ORCA_MOBILE_WEB_RENDER_BROWSER
return chromium.launch({
headless: true,
...(executablePath ? { executablePath } : {})
})
}
},
{ name: 'webkit', launch: () => webkit.launch({ headless: true }) }
]
const bundles = mobileWebAppDependenciesPresent()
const describeDrawer = bundles ? describe : describe.skip
let scratch
let server
let origin
let cspHeader = null
let bridgeVersion = null
let faultGrant = null
let backNames = null
beforeAll(async () => {
if (!bundles) {
return
}
cspHeader = await readShellCsp()
bridgeVersion = await readBridgeProtocolVersion()
faultGrant = await readBridgeFaultGrant()
backNames = await readBridgeBackNames()
scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-web-app-drawer-'))
const { outDir } = await buildMobileWebAppBundle({ outDir: join(scratch, 'bundle') })
const served = await createBundleServer({ outDir, cspHeader })
server = served.server
origin = served.origin
}, 180_000)
afterAll(async () => {
server?.close()
if (scratch) {
await rm(scratch, { recursive: true, force: true })
}
})
/** The bottom bar's Workspace options button, by its own label. */
function workspaceOptionsButton(page) {
return page.getByRole('button', { name: 'Workspace options', exact: true })
}
/** Every notify the page posted, by name, so a case can say what crossed and what did not. */
function notifyNames() {
return globalThis.__orcaRenderCheckNotifies.map((frame) => frame.name)
}
// Chromium matches Android WebView’s hardware Back; prove mounted page claims key over real bridge and closes animated sheet. WebKit has no hardware Back.
describeDrawer('the device Back key reaching a sheet on the page', () => {
it('closes the sheet instead of leaving the screen', async () => {
const browser = await ENGINES[0].launch()
try {
const page = await browser.newPage({ viewport: VIEWPORT, reducedMotion: 'no-preference' })
const errors = []
page.on('pageerror', (error) => errors.push(`${error.name}: ${error.message}`))
await page.addInitScript(installShellDouble, {
version: bridgeVersion,
sessionId: 'render-check-session',
buildId: 'render-check-build',
route: { pathname: HOST_ROUTE },
host: SHELL_HOST,
storage: {},
faultGrant,
backFrame: backNames.frame
})
await page.goto(`${origin}/`, { waitUntil: 'load' })
await page.waitForFunction(
() => document.documentElement.dataset.orcaWebEntry === 'mounted',
undefined,
{ timeout: 30_000, polling: 250 }
)
// Closed sheet claims nothing; shell retains its existing pop fallback.
expect(await page.evaluate(notifyNames)).not.toContain(backNames.claim)
await workspaceOptionsButton(page).click({ timeout: 30_000 })
await page.waitForFunction(
() => document.querySelector('[aria-label="Dismiss drawer"]') !== null,
undefined,
{ timeout: 10_000, polling: 100 }
)
const claimed = await page.waitForFunction(
(name) =>
globalThis.__orcaRenderCheckNotifies.find(
(frame) => frame.name === name && frame.claimed === true
) ?? null,
backNames.claim,
{ timeout: 10_000, polling: 100 }
)
expect(await claimed.jsonValue(), errors.join(' | ')).toMatchObject({ claimed: true })
await page.evaluate(() => {
globalThis.__orcaRenderCheckSendBack()
})
const closed = await page
.waitForFunction(
() => document.querySelector('[aria-label="Dismiss drawer"]') === null,
undefined,
{ timeout: 10_000, polling: 100 }
)
.then(() => true)
.catch(() => false)
expect(
closed,
`${errors.join(' | ')} | ${JSON.stringify(await page.evaluate(notifyNames))}`
).toBe(true)
// Consumed Back must not ask shell to pop session route as well as close sheet.
expect(await page.evaluate(notifyNames)).not.toContain(backNames.navigateBack)
// And the key goes back to the shell with the sheet, so the next press leaves the screen.
const claims = await page.evaluate(
(name) =>
globalThis.__orcaRenderCheckNotifies
.filter((frame) => frame.name === name)
.map((frame) => frame.claimed),
backNames.claim
)
expect(claims).toEqual([true, false])
expect(errors).toEqual([])
await page.close()
} finally {
await browser.close()
}
}, 120_000)
})
@@ -1,238 +0,0 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { chromium } from 'playwright-core'
import { buildMobileWebAppBundle } from '../../build/mobile-web-app/build-mobile-web-app-bundle.mjs'
import { mobileWebAppDependenciesPresent } from '../mobile-web-app-bundle-dependencies.mjs'
import {
createBundleServer,
installShellDouble,
readBridgeFaultGrant,
readBridgeProtocolVersion,
readShellCsp
} from '../preview/mobile-web-app-render-harness.mjs'
// Wide sidebar pushes Tasks through useRouteHandoff; local navigation inherits opener grants and silently refuses copy actions.
// Browser check proves control is present/reachable and shell handoff leaves document in place.
const HOST_ROUTE = '/h/render-check-host'
const HOST_PATTERN = '/h/[hostId]'
const TASKS_PATTERN = '/h/[hostId]/tasks'
/** The bundle key for the target route, so its chunk can be named rather than inferred. */
const TASKS_ROUTE_KEY = './h/[hostId]/tasks.tsx'
const FILES_PATTERN = '/h/[hostId]/files/[worktreeId]'
const SHELL_SESSION_ID = 'render-check-session'
const SHELL_BUILD_ID = 'render-check-build'
const SHELL_HOST = {
id: 'render-check-host',
name: 'Render Check Host',
endpoint: 'ws://render-check',
lastConnected: 1
}
/** The manifest's own pairs, as the shell would send them. */
const PAGE_ROUTE_GRANTS = [
{ pathname: HOST_PATTERN, grants: ['navigate', 'storage', 'externalLink', 'haptics'] },
{ pathname: FILES_PATTERN, grants: ['navigate', 'storage', 'externalLink', 'haptics'] },
{
pathname: TASKS_PATTERN,
grants: ['navigate', 'storage', 'externalLink', 'haptics', 'native.clipboard.write']
}
]
/** Wide enough for `app/h/_layout.tsx` to render the sidebar beside the route. */
const WIDE = { width: 1180, height: 820 }
const bundles = mobileWebAppDependenciesPresent()
const describeRender = bundles ? describe : describe.skip
let scratch
let server
let browser
let origin
let cspHeader = null
let bridgeVersion = null
let faultGrant = null
// Resolve target chunk from build; content-hash URLs cannot identify routes by name.
let tasksChunk = null
beforeAll(async () => {
if (!bundles) {
return
}
cspHeader = await readShellCsp()
bridgeVersion = await readBridgeProtocolVersion()
faultGrant = await readBridgeFaultGrant()
scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-web-app-handoff-'))
const built = await buildMobileWebAppBundle({ outDir: join(scratch, 'bundle') })
tasksChunk = built.routeChunks[TASKS_ROUTE_KEY]
// Require resolvable target chunk or every absence assertion could pass on a typo.
expect(tasksChunk, `no chunk for ${TASKS_ROUTE_KEY}`).toBeTruthy()
const served = await createBundleServer({ outDir: built.outDir, cspHeader })
server = served.server
origin = served.origin
const executablePath = process.env.ORCA_MOBILE_WEB_RENDER_BROWSER
browser = await chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}) })
}, 180_000)
afterAll(async () => {
await browser?.close()
server?.close()
if (scratch) {
await rm(scratch, { recursive: true, force: true })
}
})
/** Opens the worktree list at a viewport, under a named set of session grants. */
async function openHostRoute({
viewport,
grants,
pageRouteGrants = PAGE_ROUTE_GRANTS,
route = HOST_ROUTE,
awaitText = SHELL_HOST.name,
ownsHostArea = false
}) {
const page = await browser.newPage({ viewport })
await page.addInitScript(installShellDouble, {
version: bridgeVersion,
sessionId: SHELL_SESSION_ID,
buildId: SHELL_BUILD_ID,
route: { pathname: route },
host: SHELL_HOST,
storage: {},
faultGrant,
grants,
pageRoutes: [HOST_PATTERN, FILES_PATTERN, TASKS_PATTERN],
pageRouteGrants,
ownsHostArea
})
const errors = []
// Record every response status: failed chunk fetches must count as requests, not false evidence of no navigation.
const jsResponses = []
page.on('pageerror', (error) => errors.push(`${error.name}: ${error.message}`))
page.on('console', (message) => {
if (message.type() === 'error') {
errors.push(`console.error: ${message.text()}`)
}
})
page.on('response', (response) => {
const path = new URL(response.url()).pathname
if (!path.endsWith('.js')) {
return
}
jsResponses.push({ status: response.status(), path })
})
await page.goto(`${origin}/`, { waitUntil: 'load' })
await page.waitForFunction(() => document.documentElement.dataset.orcaWebEntry === 'mounted', {
timeout: 30_000,
polling: 250
})
await page.waitForFunction((needle) => document.body.innerText.includes(needle), awaitText, {
timeout: 30_000,
polling: 250
})
return { page, errors, jsResponses }
}
/** Every `navigate` notify the page posted, in order. */
function navigates(page) {
return page.evaluate(() =>
(globalThis.__orcaRenderCheckNotifies ?? []).filter((frame) => frame.name === 'navigate')
)
}
// Race navigation wait with page errors; React Navigation throws once blanked document and hid behind a bare 30s timeout.
/** Tasks sits in the host header's ⋯ menu; open the menu and pick it, as a user does. */
async function openTasksFromHeader(
page,
more = page.getByRole('button', { name: 'More actions', exact: true }).first()
) {
await more.click()
await page.getByRole('menuitem', { name: 'Tasks', exact: true }).click()
}
async function waitForTasksRoute(page, opened, clickedAt) {
try {
await page.waitForFunction(() => location.pathname.endsWith('/tasks'), {
timeout: 30_000,
polling: 250
})
} catch (cause) {
const seen = await page.evaluate(() => ({
pathname: location.pathname,
text: document.body.innerText.slice(0, 300)
}))
throw new Error(
[
`the document never reached /tasks; pathname is ${seen.pathname}`,
`page errors: ${JSON.stringify(opened.errors)}`,
`navigate notifies: ${JSON.stringify(await navigates(page))}`,
`body text: ${JSON.stringify(seen.text)}`,
`js responses since the click: ${JSON.stringify(opened.jsResponses.slice(clickedAt))}`
].join('\n'),
{ cause }
)
}
}
describeRender('the sidebar hop to tasks, under the session it was opened with', () => {
it('hands the hop to the shell when the session cannot cover tasks', async () => {
const opened = await openHostRoute({
viewport: WIDE,
grants: [faultGrant, 'navigate', 'storage', 'haptics']
})
const { page, errors, jsResponses } = opened
// The header's own menu, by the names a user reads; it is the sidebar's on a wide layout.
await openTasksFromHeader(page)
await expect
.poll(() => navigates(page))
.toEqual([
{ v: bridgeVersion, type: 'notify', name: 'navigate', href: `${HOST_ROUTE}/tasks` }
])
expect(await navigates(page)).toEqual([
{ v: bridgeVersion, type: 'notify', name: 'navigate', href: `${HOST_ROUTE}/tasks` }
])
// Require original route and no target-chunk request at any status; opener chunks can still arrive after click and must not count as target navigation.
expect(await page.evaluate(() => location.pathname)).toBe(HOST_ROUTE)
expect(jsResponses.filter(({ path }) => path.endsWith(tasksChunk))).toEqual([])
expect(errors).toEqual([])
await page.close()
}, 60_000)
it('keeps the hop in the document when the session covers tasks', async () => {
// Grant-positive control proves the same tap can navigate; absence alone could pass on an inert page.
const opened = await openHostRoute({
viewport: WIDE,
grants: [
faultGrant,
'navigate',
'storage',
'externalLink',
'haptics',
'native.clipboard.write'
]
})
const { page, errors } = opened
const clickedAt = opened.jsResponses.length
await openTasksFromHeader(page)
await waitForTasksRoute(page, opened, clickedAt)
expect(await navigates(page)).toEqual([])
expect(errors).toEqual([])
await page.close()
}, 60_000)
it('keeps the old behaviour when the shell sent no pairs at all', async () => {
// Older shells omit coverage field; absence must not force every hop into shell handoff.
const opened = await openHostRoute({
viewport: WIDE,
grants: [faultGrant, 'navigate', 'storage', 'haptics'],
pageRouteGrants: null
})
const { page, errors } = opened
const clickedAt = opened.jsResponses.length
await openTasksFromHeader(page)
await waitForTasksRoute(page, opened, clickedAt)
expect(await navigates(page)).toEqual([])
expect(errors).toEqual([])
await page.close()
}, 60_000)
})
@@ -1,135 +0,0 @@
// Measure the shipped hairline patch at phone density in both browser engines.
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import * as esbuild from 'esbuild'
import { chromium, webkit } from 'playwright-core'
import pngjs from 'pngjs'
import {
MOBILE_WEB_APP_NATIVE_PARITY_STYLE,
MOBILE_WEB_APP_ROOT_RESET,
mobileWebAppBuildOptions
} from '../../build/mobile-web-app/build-mobile-web-app-bundle.mjs'
import { mobileWebAppDependenciesPresent } from '../mobile-web-app-bundle-dependencies.mjs'
import { createBundleServer, readShellCsp } from '../preview/mobile-web-app-render-harness.mjs'
const mobileDir = fileURLToPath(new URL('../../../../mobile', import.meta.url))
// Android’s measured 480dpi is scale 3: Chromium launch flag preserves subpixel borders, unlike Playwright emulation.
// WebKit uses emulated scale, matching iOS subpixel border paint.
const ENGINES = [
{
name: 'chromium',
launch: () => {
const executablePath = process.env.ORCA_MOBILE_WEB_RENDER_BROWSER
return chromium.launch({
headless: true,
args: ['--force-device-scale-factor=3'],
...(executablePath ? { executablePath } : {})
})
},
pageOptions: { viewport: null }
},
{
name: 'webkit',
launch: () => webkit.launch({ headless: true }),
pageOptions: { viewport: { width: 427, height: 952 }, deviceScaleFactor: 3 }
}
]
// Require CommonJS copy like page dependencies; importing would measure a different react-native build.
const PAGE_ENTRY = `
import { createElement as h } from 'react'
import { createRoot } from 'react-dom/client'
const { StyleSheet, View } = require('react-native')
const styles = StyleSheet.create({
separatorBox: { paddingTop: 10.1, width: 12, backgroundColor: '#ffffff' },
separator: { height: StyleSheet.hairlineWidth, backgroundColor: '#000000' }
})
createRoot(document.getElementById('root')).render(
h(View, { testID: 'separator-box', style: styles.separatorBox }, h(View, { style: styles.separator }))
)
`
const bundles = mobileWebAppDependenciesPresent()
const describeParity = bundles ? describe : describe.skip
let scratch = null
let server = null
let origin = null
const browsers = new Map()
beforeAll(async () => {
if (!bundles) {
return
}
await mkdir(join(mobileDir, '.tmp'), { recursive: true })
scratch = await mkdtemp(join(mobileDir, '.tmp', 'native-parity-render-'))
const outDir = join(scratch, 'bundle')
await mkdir(outDir, { recursive: true })
// Reuse page options except entry/chunking so dropping a builder shim fails here.
const shipped = mobileWebAppBuildOptions([])
await esbuild.build({
...shipped,
entryPoints: undefined,
stdin: { contents: PAGE_ENTRY, resolveDir: mobileDir, loader: 'js', sourcefile: 'parity.js' },
splitting: false,
write: true,
outdir: outDir,
entryNames: 'parity',
metafile: false
})
await writeFile(
join(outDir, 'index.html'),
`<!doctype html><html><head><meta charset="utf-8">${MOBILE_WEB_APP_ROOT_RESET}` +
`${MOBILE_WEB_APP_NATIVE_PARITY_STYLE}</head><body><div id="root"></div>` +
'<script type="module" src="/parity.js"></script></body></html>'
)
const served = await createBundleServer({ outDir, cspHeader: await readShellCsp() })
server = served.server
origin = served.origin
for (const engine of ENGINES) {
browsers.set(engine.name, await engine.launch())
}
}, 180_000)
afterAll(async () => {
for (const browser of browsers.values()) {
await browser.close()
}
server?.close()
if (scratch) {
await rm(scratch, { recursive: true, force: true })
}
})
async function openPage(engine) {
const page = await browsers.get(engine.name).newPage(engine.pageOptions)
await page.goto(`${origin}/`, { waitUntil: 'domcontentloaded' })
await page.waitForSelector('[data-testid="separator-box"]')
return page
}
describeParity.each(ENGINES)('the page against native, at a phone density, in $name', (engine) => {
it('paints a StyleSheet.hairlineWidth-tall separator one device pixel tall at a fractional offset', async () => {
const page = await openPage(engine)
try {
// At 10.1 CSS px, 0.5px separator straddles two device rows in both engines.
const shot = pngjs.PNG.sync.read(
await page.locator('[data-testid="separator-box"]').screenshot({ scale: 'device' })
)
const column = Math.floor(shot.width / 2)
let darkRows = 0
for (let y = 0; y < shot.height; y++) {
// Count pure black rows in the separator clip.
if (shot.data[(y * shot.width + column) * 4] < 16) {
darkRows++
}
}
expect(darkRows).toBe(1)
} finally {
await page.close()
}
})
})
@@ -1,177 +0,0 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { chromium } from 'playwright-core'
import { buildMobileWebAppBundle } from '../../build/mobile-web-app/build-mobile-web-app-bundle.mjs'
import { mobileWebAppDependenciesPresent } from '../mobile-web-app-bundle-dependencies.mjs'
import {
createBundleServer,
installShellDouble,
readBridgeFaultGrant,
readBridgeProtocolVersion,
readShellCsp
} from '../preview/mobile-web-app-render-harness.mjs'
// Measure real Expo providers/navigators: screens/root must pad edge-to-edge page exactly once from shell init insets.
const HOST_ROUTE = '/h/render-check-host'
const HOST = {
id: 'render-check-host',
name: 'Render Check Host',
endpoint: 'ws://render-check',
lastConnected: 1
}
const INSETS = { top: 40, right: 0, bottom: 30, left: 0 }
// Use browser env insets different from shell INSETS so wrong provider cannot pass.
const ENV_INSETS = { top: 17, right: 0, bottom: 11, left: 0 }
const bundles = mobileWebAppDependenciesPresent()
const describeRender = bundles ? describe : describe.skip
let scratch
let server
let browser
let origin
let bridgeVersion
let faultGrant
beforeAll(async () => {
bridgeVersion = await readBridgeProtocolVersion()
faultGrant = await readBridgeFaultGrant()
if (!bundles) {
return
}
scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-web-app-safe-area-'))
const { outDir } = await buildMobileWebAppBundle({ outDir: join(scratch, 'bundle') })
const served = await createBundleServer({ outDir, cspHeader: await readShellCsp() })
server = served.server
origin = served.origin
const executablePath = process.env.ORCA_MOBILE_WEB_RENDER_BROWSER
browser = await chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}) })
}, 180_000)
afterAll(async () => {
await browser?.close()
server?.close()
if (scratch) {
await rm(scratch, { recursive: true, force: true })
}
})
async function openHostRoute(safeAreaInsets, envInsets = ENV_INSETS) {
const page = await browser.newPage({ viewport: { width: 390, height: 844 } })
const errors = []
page.on('pageerror', (error) => errors.push(`${error.name}: ${error.message}`))
const cdp = await page.context().newCDPSession(page)
await cdp.send('Emulation.setSafeAreaInsetsOverride', { insets: envInsets })
await page.addInitScript(installShellDouble, {
version: bridgeVersion,
sessionId: 'safe-area-session',
buildId: 'safe-area-build',
route: { pathname: HOST_ROUTE },
host: HOST,
storage: {},
faultGrant,
grants: [faultGrant],
safeAreaInsets
})
await page.goto(`${origin}/`, { waitUntil: 'load' })
await page.waitForFunction((name) => document.body.innerText.includes(name), HOST.name, {
timeout: 30_000,
polling: 250
})
return { page, errors }
}
function readEdges(page) {
return page.evaluate((name) => {
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT)
// The list's page title is the last copy of the name; the bar holds a hidden one until the list scrolls.
let title = null
for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
if (node.textContent === name) {
title = node
}
}
const range = document.createRange()
if (title !== null) {
range.selectNodeContents(title)
}
const fab = [...document.querySelectorAll('[role="button"]')].find(
(element) => element.getAttribute('aria-label') === 'New workspace'
)
return {
titleTop: title === null ? null : range.getBoundingClientRect().top,
titleLeft: title === null ? null : range.getBoundingClientRect().left,
fabBottom: fab?.getBoundingClientRect().bottom ?? null,
fabRight: fab?.getBoundingClientRect().right ?? null,
envTop: (() => {
const probe = document.createElement('div')
probe.style.paddingTop = 'env(safe-area-inset-top)'
document.body.append(probe)
const top = getComputedStyle(probe).paddingTop
probe.remove()
return top
})(),
viewportHeight: window.innerHeight
}
}, HOST.name)
}
describeRender('the page pads for the system bars once, by the shell insets', () => {
it('moves the header by exactly the inset init carried, not by the browser env', async () => {
const bare = await openHostRoute(null)
const zero = await readEdges(bare.page)
await bare.page.close()
const inset = await openHostRoute(INSETS)
const padded = await readEdges(inset.page)
await inset.page.close()
const noEnv = await openHostRoute(null, { top: 0, right: 0, bottom: 0, left: 0 })
const envless = await readEdges(noEnv.page)
await noEnv.page.close()
expect([...bare.errors, ...inset.errors, ...noEnv.errors]).toEqual([])
expect(zero.titleTop).not.toBeNull()
expect([zero.envTop, envless.envTop]).toEqual([`${ENV_INSETS.top}px`, '0px'])
expect(zero.titleTop).toBe(envless.titleTop)
// Require shell pad exactly once: DefaultNavigator adds browser env pad, while wrong web provider substitutes it.
expect(padded.titleTop - zero.titleTop).toBe(INSETS.top)
}, 90_000)
// Unequal landscape side insets catch swapped sensor-housing edge.
it('keeps the screens clear of the side insets, padding them once', async () => {
const upright = await openHostRoute(INSETS)
const base = await readEdges(upright.page)
await upright.page.close()
const sideways = await openHostRoute({ ...INSETS, left: 59, right: 44 })
const inset = await readEdges(sideways.page)
await sideways.page.close()
expect([...upright.errors, ...sideways.errors]).toEqual([])
expect(inset.titleLeft - base.titleLeft).toBe(59)
expect(base.fabRight - inset.fabRight).toBe(44)
}, 60_000)
it('follows a re-sent init, which is how the keyboard and rotation reach the page', async () => {
const opened = await openHostRoute(INSETS)
const before = await readEdges(opened.page)
await opened.page.evaluate(
(insets) => {
globalThis.__orcaRenderCheckResendInit({ safeAreaInsets: insets })
},
{ ...INSETS, top: 64 }
)
await opened.page.waitForFunction(
({ name, top }) => {
const found = [...document.querySelectorAll('*')].some(
(element) => element.textContent === name && element.getBoundingClientRect().top > top
)
return found
},
{ name: HOST.name, top: before.titleTop + 10 },
{ timeout: 10_000, polling: 100 }
)
const after = await readEdges(opened.page)
await opened.page.close()
expect(opened.errors).toEqual([])
expect(after.titleTop - before.titleTop).toBe(64 - INSETS.top)
}, 60_000)
})
@@ -1,233 +0,0 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { chromium } from 'playwright-core'
import { buildMobileWebAppBundle } from '../../build/mobile-web-app/build-mobile-web-app-bundle.mjs'
import { mobileWebAppDependenciesPresent } from '../mobile-web-app-bundle-dependencies.mjs'
import { MOBILE_WEB_PAGE_ROUTES } from '../../build/mobile-web-app/mobile-web-page-routes.mjs'
import {
createBundleServer,
installShellDouble,
readBridgeFaultGrant,
readBridgeProtocolVersion,
readShellCsp
} from '../preview/mobile-web-app-render-harness.mjs'
// Serve real-shaped tab snapshot and terminal stream; no-RPC session-render never attaches terminal.
// Surface exists at mount but grid opens only after init. Placeholder client identity gates terminal.subscribe; null once left surface 0×0.
// One test pins subscription identity and another reads painted grid, avoiding chrome-only false passes.
const HOST_ID = 'terminal-init-host'
const WORKTREE = 'wt-1'
const SESSION_ROUTE = `/h/${HOST_ID}/session/${WORKTREE}`
const SESSION_PATTERN = '/h/[hostId]/session/[worktreeId]'
const PAGE_ROUTE_PATTERNS = [SESSION_PATTERN]
const SHELL_SESSION_ID = 'terminal-init-session'
const SHELL_BUILD_ID = 'terminal-init-build'
const SHELL_HOST = {
id: HOST_ID,
name: 'Terminal Init Host',
endpoint: 'ws://terminal-init',
lastConnected: 1
}
const HANDLE = 'pty-handle-terminal-init'
const TAB_ID = 'tab-terminal-init'
const SCROLLBACK_MARKER = 'orca-terminal-init-marker'
const TABS_SNAPSHOT = {
type: 'snapshot',
worktree: `id:${WORKTREE}`,
publicationEpoch: 'terminal-init-epoch',
snapshotVersion: 1,
activeTabId: TAB_ID,
activeTabType: 'terminal',
tabs: [
{
type: 'terminal',
id: TAB_ID,
title: 'bash',
terminal: HANDLE,
status: 'ready',
isActive: true
}
]
}
const SCROLLBACK_EVENT = {
type: 'scrollback',
seq: 1,
cols: 80,
rows: 24,
serialized: `${SCROLLBACK_MARKER}\r\n`,
displayMode: 'phone'
}
// Read manifest grants so fixture stays aligned with route.
function sessionGrants() {
const declared = MOBILE_WEB_PAGE_ROUTES.find((route) => route.pathname === SESSION_PATTERN)
if (!declared) {
throw new Error(`${SESSION_PATTERN} is not registered`)
}
return declared.grants
}
const bundles = mobileWebAppDependenciesPresent()
const describeRender = bundles ? describe : describe.skip
let scratch
let server
let browser
let origin
let cspHeader = null
let bridgeVersion = null
let faultGrant = null
beforeAll(async () => {
if (!bundles) {
return
}
cspHeader = await readShellCsp()
bridgeVersion = await readBridgeProtocolVersion()
faultGrant = await readBridgeFaultGrant()
scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-web-app-terminal-init-'))
const built = await buildMobileWebAppBundle({ outDir: join(scratch, 'bundle') })
const served = await createBundleServer({ outDir: built.outDir, cspHeader })
server = served.server
origin = served.origin
const executablePath = process.env.ORCA_MOBILE_WEB_RENDER_BROWSER
browser = await chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}) })
}, 600_000)
afterAll(async () => {
await browser?.close()
server?.close()
if (scratch) {
await rm(scratch, { recursive: true, force: true })
}
})
// Answer minimum startup reads and name both streams so assertions observe loaded session, not refusal/retry states.
async function openSessionWithTerminalTab() {
const page = await browser.newPage({ viewport: { width: 390, height: 844 } })
await page.addInitScript(installShellDouble, {
version: bridgeVersion,
sessionId: SHELL_SESSION_ID,
buildId: SHELL_BUILD_ID,
route: { pathname: SESSION_ROUTE },
host: SHELL_HOST,
storage: {},
faultGrant,
grants: [faultGrant, ...sessionGrants()],
pageRoutes: PAGE_ROUTE_PATTERNS,
streams: ['session.tabs.subscribe', 'terminal.subscribe'],
replies: {
'worktree.show': { worktree: { id: WORKTREE, name: WORKTREE, path: `/tmp/${WORKTREE}` } },
'terminal.list': {
terminals: [{ handle: HANDLE, title: 'bash', worktree: `id:${WORKTREE}` }]
}
}
})
const errors = []
page.on('pageerror', (error) => errors.push(`${error.name}: ${error.message}`))
await page.goto(`${origin}/`, { waitUntil: 'load' })
await page.waitForFunction(
() => document.documentElement.dataset.orcaWebEntry === 'mounted',
undefined,
{ timeout: 60_000, polling: 250 }
)
const tabs = await waitForSubscribe(page, 'session.tabs.subscribe')
await page.evaluate(
([id, event]) => globalThis.__orcaRenderCheckEmitEvent(id, event),
[tabs.id, TABS_SNAPSHOT]
)
return { errors, page }
}
// Serialized page function closes over nothing; xterm helper textarea measures one cell where canvas/WebGL exposes no text rows.
function readTerminalGrid() {
const surface = document.getElementById('terminal-surface')
const box = surface.getBoundingClientRect()
const read = { surface: { width: Math.round(box.width), height: Math.round(box.height) } }
const screen = surface.querySelector('.xterm-screen')
const cell = surface.querySelector('.xterm-helper-textarea')
if (!screen || !cell) {
return { ...read, grid: null }
}
const cellBox = cell.getBoundingClientRect()
if (cellBox.width <= 0 || cellBox.height <= 0) {
return { ...read, grid: null }
}
const screenBox = screen.getBoundingClientRect()
return {
...read,
grid: {
cols: Math.round(screenBox.width / cellBox.width),
rows: Math.round(screenBox.height / cellBox.height)
}
}
}
async function waitForSubscribe(page, method) {
try {
await page.waitForFunction(
(name) => (globalThis.__orcaRenderCheckSubscribes ?? []).some((one) => one.method === name),
method,
// Streams normally open within a second; bound failure reporting with headroom rather than adding fixed wait.
{ timeout: 30_000, polling: 100 }
)
} catch {
const opened = await page.evaluate(() => globalThis.__orcaRenderCheckSubscribes ?? [])
throw new Error(
`the page never subscribed to ${method}; it opened: ${
opened.map((one) => one.method).join(', ') || 'nothing'
}`
)
}
const found = await page.evaluate(
(name) => (globalThis.__orcaRenderCheckSubscribes ?? []).find((one) => one.method === name),
method
)
return found
}
describeRender(
'the session route attaches its terminal on the page',
() => {
it('receives init in the document and measures a non-zero grid', async () => {
const { errors, page } = await openSessionWithTerminalTab()
const subscribe = await waitForSubscribe(page, 'terminal.subscribe')
await page.evaluate(
([id, event]) => globalThis.__orcaRenderCheckEmitEvent(id, event),
[subscribe.id, SCROLLBACK_EVENT]
)
// Require xterm-screen created by init/term.open, not surface present at mount.
// Await replay/resize before reading one-cell helper textarea; screen existence can precede measurable grid.
await page.waitForFunction(
() => {
const cell = document.querySelector('#terminal-surface .xterm-helper-textarea')
return (
document.querySelector('.xterm-screen') !== null &&
cell !== null &&
cell.getBoundingClientRect().width > 0
)
},
undefined,
{
timeout: 60_000,
polling: 250
}
)
const painted = await page.evaluate(readTerminalGrid)
console.log('[terminal-init]', JSON.stringify(painted))
// Catch emulator’s original 0×0 surface failure.
expect(painted.surface.width).toBeGreaterThan(0)
expect(painted.surface.height).toBeGreaterThan(0)
// Match scrollback grid dimensions to reject defaults; terminal-render separately checks buffer bytes because WebGL exposes no text rows.
expect(painted.grid).toEqual({ cols: SCROLLBACK_EVENT.cols, rows: SCROLLBACK_EVENT.rows })
expect(errors).toEqual([])
await page.close()
}, 300_000)
},
900_000
)
@@ -1,196 +0,0 @@
import { execFileSync, spawn } from 'node:child_process'
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
killProcessMatchingCommand,
killRecordedAndMatchingProcesses,
killRecordedProcess,
signalValidatedProcessGroup,
writeProcessRecord
} from './macos-computer-helper-owner-loss-processes.mjs'
const describeMacOS = process.platform === 'darwin' ? describe : describe.skip
const spawnedPids = new Set()
const temporaryDirectories = new Set()
afterEach(() => {
for (const pid of spawnedPids) {
try {
process.kill(pid, 'SIGKILL')
} catch {}
}
spawnedPids.clear()
for (const temporaryDirectory of temporaryDirectories) {
rmSync(temporaryDirectory, { recursive: true, force: true })
}
temporaryDirectories.clear()
})
describeMacOS('macOS helper owner-loss benchmark process cleanup', () => {
it('kills a timed-out trial group only after validating its environment', async () => {
const temporaryDirectory = mkdtempSync(path.join(tmpdir(), 'orca-owner-benchmark-group-test-'))
temporaryDirectories.add(temporaryDirectory)
const childPidPath = path.join(temporaryDirectory, 'child.pid')
const environmentName = `ORCA_OWNER_GROUP_${process.pid}`
const environmentValue = `${Date.now()}`
const fixture = `
const { spawn } = require('node:child_process')
const { writeFileSync } = require('node:fs')
const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], {
stdio: 'ignore'
})
writeFileSync(${JSON.stringify(childPidPath)}, String(child.pid))
setInterval(() => {}, 1000)
`
const launcher = spawn(process.execPath, ['-e', fixture], {
detached: true,
env: { ...process.env, [environmentName]: environmentValue },
stdio: 'ignore'
})
spawnedPids.add(launcher.pid)
launcher.unref()
const launcherExited = new Promise((resolve) => launcher.once('exit', resolve))
await expect.poll(() => existsSync(childPidPath), { timeout: 10_000 }).toBe(true)
const childPid = Number(readFileSync(childPidPath, 'utf8'))
spawnedPids.add(childPid)
// Send the trial timeout's own kill signal once the group is up; a real timeout would race its startup.
process.kill(launcher.pid, 'SIGKILL')
await launcherExited
spawnedPids.delete(launcher.pid)
const environmentFragment = `${environmentName}=${environmentValue}`
const groupState = { stopped: false }
expect(() => process.kill(launcher.pid, 0)).toThrow()
expect(() =>
signalValidatedProcessGroup(launcher.pid, `${environmentName}=wrong`, 'SIGSTOP')
).toThrow('Benchmark process group no longer belongs to this trial')
expect(() => process.kill(childPid, 0)).not.toThrow()
expect(
signalValidatedProcessGroup(launcher.pid, environmentFragment, 'SIGSTOP', groupState)
).toBe(true)
expect(
signalValidatedProcessGroup(launcher.pid, environmentFragment, 'SIGKILL', groupState)
).toBe(true)
await expect
.poll(() => {
try {
process.kill(childPid, 0)
return true
} catch {
return false
}
})
.toBe(false)
spawnedPids.delete(childPid)
})
it('kills a recorded helper in a separate process group', async () => {
const temporaryDirectory = mkdtempSync(
path.join(tmpdir(), 'orca-owner-benchmark-cleanup-test-')
)
temporaryDirectories.add(temporaryDirectory)
const recordPath = path.join(temporaryDirectory, 'helper.json')
const marker = `orca-owner-cleanup-${process.pid}-${Date.now()}`
const helper = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1_000)', marker], {
detached: true,
stdio: 'ignore'
})
spawnedPids.add(helper.pid)
helper.unref()
const exited = new Promise((resolve) => helper.once('exit', resolve))
const command = execFileSync('ps', ['-p', String(helper.pid), '-o', 'command='], {
encoding: 'utf8'
}).trim()
const processGroup = Number(
execFileSync('ps', ['-p', String(helper.pid), '-o', 'pgid='], {
encoding: 'utf8'
}).trim()
)
writeProcessRecord(recordPath, { pid: helper.pid, pgid: processGroup, command })
expect(processGroup).toBe(helper.pid)
expect(killRecordedProcess(recordPath, marker)).toBe(true)
await exited
expect(() => process.kill(helper.pid, 0)).toThrow()
spawnedPids.delete(helper.pid)
})
it('kills every unrecorded helper using its unique trial command', async () => {
const marker = `orca-owner-unrecorded-${process.pid}-${Date.now()}`
const helpers = Array.from({ length: 2 }, () =>
spawn(process.execPath, ['-e', 'setInterval(() => {}, 1_000)', marker], {
detached: true,
stdio: 'ignore'
})
)
for (const helper of helpers) {
spawnedPids.add(helper.pid)
helper.unref()
}
const exited = Promise.all(
helpers.map((helper) => new Promise((resolve) => helper.once('exit', resolve)))
)
expect(killProcessMatchingCommand([process.execPath, marker])).toBe(true)
await exited
for (const helper of helpers) {
expect(() => process.kill(helper.pid, 0)).toThrow()
spawnedPids.delete(helper.pid)
}
})
it('runs unique-command cleanup after an invalid process record', async () => {
const temporaryDirectory = mkdtempSync(
path.join(tmpdir(), 'orca-owner-benchmark-fallback-test-')
)
temporaryDirectories.add(temporaryDirectory)
const recordPath = path.join(temporaryDirectory, 'helper.json')
const marker = `orca-owner-invalid-record-${process.pid}-${Date.now()}`
const helper = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1_000)', marker], {
detached: true,
stdio: 'ignore'
})
spawnedPids.add(helper.pid)
helper.unref()
const exited = new Promise((resolve) => helper.once('exit', resolve))
const command = execFileSync('ps', ['-p', String(helper.pid), '-o', 'command='], {
encoding: 'utf8'
}).trim()
writeProcessRecord(recordPath, { pid: helper.pid, pgid: helper.pid - 1, command })
expect(() =>
killRecordedAndMatchingProcesses(recordPath, marker, [process.execPath, marker])
).toThrow('Recorded benchmark helper identity is invalid')
await exited
expect(() => process.kill(helper.pid, 0)).toThrow()
spawnedPids.delete(helper.pid)
})
it('rejects a record that is not a detached process-group identity', () => {
const temporaryDirectory = mkdtempSync(
path.join(tmpdir(), 'orca-owner-benchmark-identity-test-')
)
temporaryDirectories.add(temporaryDirectory)
const recordPath = path.join(temporaryDirectory, 'helper.json')
const marker = `orca-owner-invalid-identity-${process.pid}-${Date.now()}`
const helper = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1_000)', marker], {
stdio: 'ignore'
})
spawnedPids.add(helper.pid)
helper.unref()
const command = execFileSync('ps', ['-p', String(helper.pid), '-o', 'command='], {
encoding: 'utf8'
}).trim()
writeProcessRecord(recordPath, { pid: helper.pid, pgid: helper.pid - 1, command })
expect(() => killRecordedProcess(recordPath, marker)).toThrow(
'Recorded benchmark helper identity is invalid'
)
expect(() => process.kill(helper.pid, 0)).not.toThrow()
})
})
@@ -6,7 +6,6 @@ const NODE_RUNTIME_INCLUDE = [
'tests/e2e/linear-cli-recovery.unit.test.ts',
// Exercises a real peer reset through Node's native Socket.setTypeOfService.
'src/main/network/best-effort-socket-type-of-service.test.ts',
'src/main/runtime/agent-session/lifecycle/structured-agent-cli-writers.test.ts',
'config/scripts/ci/workflow-contracts/cloud-security-history-workflow.test.mjs',
'src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent-shell.integration.test.ts',
'src/main/ssh/remote-exec/ssh-remote-commands.test.ts',
@@ -130,7 +129,6 @@ const NODE_RUNTIME_INCLUDE = [
'src/main/agent-hooks/server/testing/identity/server-hook-session-binding.test.ts',
'tests/e2e/helpers/persisted-profile-state.unit.test.ts',
'src/main/runtime/push/notifications/mobile-notification-dismissal-store.test.ts',
'src/main/runtime/push/notifications/mobile-notification-dismissal-read-failure.test.ts',
'src/main/ipc/notifications-external-acknowledgement.test.ts'
]
@@ -27,7 +27,6 @@ export const SHELL_PREFIXES = [
'src/shared/shell/wsl/fish-wsl-cwd-report',
'src/shared/shell/testing/fish-binary-requirement',
'src/shared/terminal/pty/ingress/pty-reply-echo-shapes',
'src/shared/shell/launch/startup-shell-portability',
'src/shared/shell/command-resolution/posix-command-path-lookup',
'src/shared/agent-launch/startup/readiness/draft-paste-ready-scanner.ts',
'src/main/wsl/filesystem/wsl-shell-cwd-report',
@@ -1,73 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { ClaudeUsageDailyAggregate, ClaudeUsagePersistedState } from './types'
import { buildBreakdown, buildSummary } from './claude-usage-report-aggregation'
function dailyRow(day: string, model: string): ClaudeUsageDailyAggregate {
return {
day,
model,
projectKey: 'project',
projectLabel: 'project',
repoId: null,
worktreeId: 'worktree-1',
turnCount: 1,
zeroCacheReadTurnCount: 0,
inputTokens: 1_000_000,
outputTokens: 1_000_000,
cacheReadTokens: 0,
cacheWriteTokens: 0,
cacheWrite1hTokens: 0
}
}
function stateWithDaily(dailyAggregates: ClaudeUsageDailyAggregate[]): ClaudeUsagePersistedState {
return {
schemaVersion: 6,
worktreeFingerprint: null,
processedFiles: [],
sessions: [],
dailyAggregates,
scanState: {
enabled: true,
lastScanStartedAt: null,
lastScanCompletedAt: null,
lastScanError: null
}
}
}
describe('buildSummary unpriced models', () => {
it('keeps the priced total and flags the rows it had to leave out', () => {
const summary = buildSummary(
stateWithDaily([
dailyRow('2026-10-15', 'claude-sonnet-5-5'),
dailyRow('2026-10-15', 'claude-opus-9')
]),
'all',
'all'
)
expect(summary.estimatedCostUsd).toBeCloseTo(12)
expect(summary.hasUnpricedModels).toBe(true)
})
})
describe('buildSummary Haiku 5.5 long-context requests', () => {
it('bills only the requests recorded over 100K at the long-context rates', () => {
const row = {
...dailyRow('2026-10-15', 'claude-haiku-5-5'),
longContext: {
inputTokens: 500_000,
outputTokens: 0,
cacheReadTokens: 0,
cacheWriteTokens: 0,
cacheWrite1hTokens: 0
}
}
const state = stateWithDaily([row])
expect(buildSummary(state, 'all', 'all').estimatedCostUsd).toBeCloseTo(0.8)
expect(buildSummary(state, 'all', 'all').hasUnpricedModels).toBe(false)
expect(buildBreakdown(state, 'all', 'all', 'model')[0]?.estimatedCostUsd).toBeCloseTo(0.8)
})
})
@@ -1,59 +0,0 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { hasCustomCodexHomeOverrideForLaunch } from './codex-real-home-path'
import { __resetShellStartupEnvCache } from '../../../pty/shell-startup/shell-startup-env'
const temporaryHomes: string[] = []
const savedConfigHome = process.env.XDG_CONFIG_HOME
afterEach(() => {
__resetShellStartupEnvCache()
if (savedConfigHome === undefined) {
delete process.env.XDG_CONFIG_HOME
} else {
process.env.XDG_CONFIG_HOME = savedConfigHome
}
for (const path of temporaryHomes.splice(0)) {
rmSync(path, { recursive: true, force: true })
}
})
describe('hasCustomCodexHomeOverride', () => {
it.skipIf(process.platform === 'win32')(
'detects a pane-local shell startup override from its launch HOME',
() => {
const paneHome = mkdtempSync(join(tmpdir(), 'orca-codex-pane-home-'))
temporaryHomes.push(paneHome)
writeFileSync(join(paneHome, '.zshrc'), 'export CODEX_HOME="$HOME/custom-codex-home"\n')
expect(hasCustomCodexHomeOverrideForLaunch({ HOME: paneHome, SHELL: '/bin/zsh' })).toBe(true)
}
)
// Dock launches may lack XDG_CONFIG_HOME exported by fish; use the pane launch environment.
it.skipIf(process.platform === 'win32')(
'resolves a fish override under the launch env XDG_CONFIG_HOME, not the process one',
() => {
const paneHome = mkdtempSync(join(tmpdir(), 'orca-codex-fish-home-'))
temporaryHomes.push(paneHome)
const configHome = join(paneHome, 'xdg')
mkdirSync(join(configHome, 'fish'), { recursive: true })
writeFileSync(
join(configHome, 'fish', 'config.fish'),
'set -gx CODEX_HOME "$HOME/custom-codex-home"\n'
)
delete process.env.XDG_CONFIG_HOME
const launchEnv = {
HOME: paneHome,
SHELL: '/opt/homebrew/bin/fish',
XDG_CONFIG_HOME: configHome
}
expect(hasCustomCodexHomeOverrideForLaunch(launchEnv)).toBe(true)
}
)
})
@@ -1,64 +0,0 @@
import { beforeEach, expect, it, vi } from 'vitest'
import type { DaemonAsyncIoStatus } from '../../../shared/terminal/daemon/daemon-async-io-health'
const { handlers, provider, adapter, restart } = vi.hoisted(() => ({
handlers: new Map<string, () => Promise<DaemonAsyncIoStatus>>(),
provider: vi.fn(),
adapter: { getDaemonIdentity: vi.fn(), getAsyncIoHealth: vi.fn() },
restart: vi.fn()
}))
vi.mock('electron', () => ({
ipcMain: {
removeHandler: (name: string) => handlers.delete(name),
handle: (name: string, handler: () => Promise<DaemonAsyncIoStatus>) =>
handlers.set(name, handler)
}
}))
vi.mock('../../daemon/providers/lifecycle/daemon-provider-state', () => ({
getDaemonProvider: provider
}))
vi.mock('../../daemon/providers/lifecycle/daemon-provider-routing', () => ({
getCurrentDaemonAdapter: () => adapter
}))
vi.mock('../../daemon/providers/lifecycle/daemon-provider-restart', () => ({
restartDaemon: restart
}))
import { registerDaemonManagementHandlers } from './pty-management'
beforeEach(() => {
vi.clearAllMocks()
provider.mockReturnValue({})
// Real adapters return a fresh copy on every read.
adapter.getDaemonIdentity.mockImplementation(() => ({
pid: 123,
startedAtMs: 1,
launchNonce: 'original'
}))
adapter.getAsyncIoHealth.mockResolvedValue({ state: 'stalled', pendingMs: 5000 })
registerDaemonManagementHandlers()
})
async function read(): Promise<DaemonAsyncIoStatus | undefined> {
return handlers.get('pty:management:asyncIoHealth')?.()
}
it('discards health evidence if the daemon changes while the check is pending', async () => {
let finish: (health: DaemonAsyncIoStatus) => void = () => {}
adapter.getAsyncIoHealth.mockImplementationOnce(
() =>
new Promise<DaemonAsyncIoStatus>((resolve) => {
finish = resolve
})
)
const pending = read()
adapter.getDaemonIdentity.mockReturnValue({
pid: 456,
startedAtMs: 2,
launchNonce: 'replacement'
})
finish({ state: 'stalled', pendingMs: 5000 })
expect(await pending).toEqual({ state: 'unverifiable' })
expect(restart).not.toHaveBeenCalled()
})
@@ -1,52 +0,0 @@
import { spawnSync } from 'node:child_process'
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { orcadLivenessProbeCommand, parseOrcadLiveness } from './orcad-remote-launch'
import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform'
const posix = getRemoteHostPlatform('linux-x64')
getRemoteHostPlatform('win32-x64')
JSON.stringify({
type: 'orca_server_ready',
schemaVersion: 1,
runtimeId: 'r1',
boundEndpoint: 'ws://127.0.0.1:7777',
advertisedEndpoint: null,
managedWslCliReconciliation: 'settled',
pairing: { available: false, reason: 'disabled_by_operator', guidance: 'n/a' },
health: { buildHash: 'abc', terminalDaemon: { state: 'live' } }
})
describe('liveness', () => {
// Real host (win-lowspec): after a distro restart the probe's own shell took the recorded PID.
describe.skipIf(process.platform === 'win32')(
'a recorded PID after a restart (real shell)',
() => {
const probeIn = (script: string): string =>
spawnSync('sh', ['-c', script], { encoding: 'utf8' }).stdout
async function withSlot(run: (slot: string, probe: string) => Promise<void>): Promise<void> {
const slot = mkdtempSync(join(tmpdir(), 'orcad-liveness-'))
try {
await run(slot, orcadLivenessProbeCommand(posix, slot))
} finally {
rmSync(slot, { recursive: true, force: true })
}
}
it('calls dead a PID held by the probe shell or the shell wrapping it', async () => {
await withSlot(async (slot, probe) => {
const own = probeIn(`echo $$ > '${slot}/.orcad-pid'; ${probe}`)
expect(parseOrcadLiveness(own)).toBe('DEAD')
// The trailing `:` stops dash and bash from exec'ing the inner shell into the outer's PID.
const wrapped = probeIn(
`echo $$ > '${slot}/.orcad-pid'; sh -c ${JSON.stringify(probe).replace(/\$/g, '\\$')}; :`
)
expect(parseOrcadLiveness(wrapped)).toBe('DEAD')
})
})
}
)
})
@@ -1,48 +0,0 @@
import { describe, expect, it } from 'vitest'
import { agentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
import {
createLegacyProviderTimelineIdentityScheme,
providerTimelineKeyPart,
spellProviderTimelineKey
} from './provider-timeline-identity'
const scheme = createLegacyProviderTimelineIdentityScheme({ agent: 'grok', sessionId: 's1' })
const provider = (value: string) => ({ source: 'provider', value }) as const
describe('provider timeline identity spelling', () => {
it('escapes a key so it cannot forge another part', () => {
expect(providerTimelineKeyPart('a:b/c')).toBe('a%3Ab%2Fc')
expect(spellProviderTimelineKey('ns', provider('x:y'))).not.toBe(
spellProviderTimelineKey('ns:x', provider('y'))
)
})
it('bounds a long key by a digest, so two long keys with one prefix stay apart', () => {
const head = 'k'.repeat(400)
const one = providerTimelineKeyPart(`${head}1`)
const two = providerTimelineKeyPart(`${head}2`)
expect(Buffer.byteLength(one, 'utf8')).toBeLessThanOrEqual(256)
expect(one).not.toBe(two)
})
it('spells an item per thread, and a minted key apart from any provider one', () => {
const item = (thread: string | null) =>
agentJournalItemKey(
scheme.item({ namespace: 'ns', family: 'item', key: provider('m1'), thread })
)
expect(new Set([item(null), item('root'), item('child')]).size).toBe(3)
expect(spellProviderTimelineKey('ns', { source: 'minted', value: 'gen-1:s1' })).toBe(
'm:gen-1%3As1'
)
})
it('spells a request in the acquisition that asked it, with its incarnation', () => {
const request = (generation: string, incarnation: number) =>
scheme.request({ generation, key: '0', incarnation })
expect(request('gen-1', 1)).toMatchObject({ provider: 'legacy', recordId: 'request:g:gen-1:0' })
expect(request('gen-1', 2)).toMatchObject({ recordId: 'request:g:gen-1:0#2' })
expect(agentJournalItemKey(request('gen-2', 1))).not.toBe(
agentJournalItemKey(request('gen-1', 1))
)
})
})
@@ -1,54 +0,0 @@
import { expect, it } from 'vitest'
import { createRestTestRig } from './structured-agent-session-rest-test-rig.test-fixture'
import { claudeProfileSetupFailed } from '../../../../claude-accounts/profiles/routing/claude-profile-launch-errors'
import {
createTestParams,
CREATE_TEST_CALLER
} from './structured-agent-session-create.test-fixture'
import {
hostTestMessage,
hostTestOperationId,
hostTestAttachParams
} from './structured-agent-session-host-test-data.test-fixture'
it('refuses a reused opening message ID without creating the second session', async () => {
const rig = await createRestTestRig()
try {
const firstMessage = { clientMessageId: hostTestOperationId(), body: hostTestMessage('Hello') }
expect(
await rig.host.create(CREATE_TEST_CALLER, createTestParams(firstMessage), { firstMessage })
).toMatchObject({ ok: true })
const second = createTestParams(firstMessage, {}, 'session-second')
expect(await rig.host.create(CREATE_TEST_CALLER, second, { firstMessage })).toMatchObject({
ok: false,
refusal: { code: 'agent_session_operation_invalid', details: { reason: 'messageIdReused' } }
})
expect(rig.store.getRecord('session-second')).toBeNull()
} finally {
await rig.dispose()
}
})
it('returns a typed preparation failure on its first response and replay, then permits recovery', async () => {
const rig = await createRestTestRig()
try {
rig.adapter.acquire.mockRejectedValueOnce(claudeProfileSetupFailed())
const params = hostTestAttachParams(null)
const first = await rig.host.attach(CREATE_TEST_CALLER, params)
expect(first).toMatchObject({
ok: false,
refusal: {
code: 'agent_session_operation_invalid',
details: { reason: 'claudeAccountSetupFailed', ownerVerdict: 'exited' },
ownerVerdict: 'exited'
}
})
await expect(rig.host.attach(CREATE_TEST_CALLER, params)).resolves.toEqual(first)
await expect(
rig.host.attach(CREATE_TEST_CALLER, hostTestAttachParams(null))
).resolves.toMatchObject({ ok: true })
} finally {
await rig.dispose()
}
})
@@ -1,47 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { createAgentStatusExtensionHarness } from './agent-status-extension-test-harness'
function postedHookNames(fetchMock: ReturnType<typeof vi.fn>): string[] {
return fetchMock.mock.calls.map((call) => {
const body: { payload?: { hook_event_name?: unknown } } = JSON.parse(String(call[1]?.body))
return typeof body.payload?.hook_event_name === 'string' ? body.payload.hook_event_name : ''
})
}
async function flushPosts(): Promise<void> {
for (let i = 0; i < 20; i++) {
await Promise.resolve()
}
}
function assistantMessage(text: string): { message: Record<string, unknown> } {
return { message: { role: 'assistant', content: [{ type: 'text', text }] } }
}
// Nested settlement can start the next run first; completion tracking must remain per-run rather than one resettable latch.
describe('a follow-up run started from another extension settlement', () => {
it('still reports the follow-up run completion', async () => {
const harness = createAgentStatusExtensionHarness({ kind: 'pi' })
const context = { isIdle: vi.fn(() => true) }
await harness.callHook('agent_start', undefined, context)
await harness.callHook('agent_end', undefined, context)
await harness.callHook('agent_settled', undefined, context)
await flushPosts()
expect(postedHookNames(harness.fetchMock)).toEqual(['agent_start', 'agent_end'])
await harness.callHook('agent_start', undefined, context)
await harness.callHook('message_end', assistantMessage('all done'), context)
await harness.callHook('agent_end', undefined, context)
await harness.callHook('agent_start', undefined, context)
await harness.callHook('agent_settled', undefined, context)
await harness.callHook('message_end', assistantMessage('nothing durable to save'), context)
await harness.callHook('agent_end', undefined, context)
await harness.callHook('agent_settled', undefined, context)
await flushPosts()
const posted = postedHookNames(harness.fetchMock)
expect(posted.at(-1), `posted: ${posted.join(' -> ')}`).toBe('agent_end')
})
})
@@ -1,64 +0,0 @@
import { getEventListeners } from 'node:events'
import { describe, expect, it } from 'vitest'
import {
createAuthFilesystemOperation,
type SharedAuthFilesystemOperation
} from './auth-filesystem-operation'
function pendingOperation(): {
operation: SharedAuthFilesystemOperation<string>
resolve: (value: string) => void
reject: (reason: unknown) => void
rawCalls: () => number
} {
let resolve = (_value: string): void => {}
let reject = (_reason: unknown): void => {}
let calls = 0
const operation = createAuthFilesystemOperation('auth-retention-fixture', () => {
calls += 1
return new Promise<string>((resolveRaw, rejectRaw) => {
resolve = resolveRaw
reject = rejectRaw
})
})
return {
operation,
resolve: (value) => resolve(value),
reject: (reason) => reject(reason),
rawCalls: () => calls
}
}
async function abortWait(
operation: SharedAuthFilesystemOperation<string>
): Promise<WeakRef<Error>> {
const controller = new AbortController()
const reason = new Error('Auth poll expired')
const weakReason = new WeakRef(reason)
const result = operation.wait(controller.signal)
controller.abort(reason)
await result.catch((error: unknown) => {
if (error !== reason) {
throw new Error('Abort reason identity changed')
}
})
expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0)
return weakReason
}
describe('shared auth filesystem wait lifetime', () => {
it('preserves a live sibling and forwards raw failure identity to later waits', async () => {
const pending = pendingOperation()
const controller = new AbortController()
const live = pending.operation.wait(controller.signal)
await Promise.resolve()
await abortWait(pending.operation)
const reason = new Error('Raw filesystem failure')
const rejected = expect(live).rejects.toBe(reason)
pending.reject(reason)
await rejected
await expect(pending.operation.wait(controller.signal)).rejects.toBe(reason)
expect(pending.rawCalls()).toBe(1)
expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0)
})
})
@@ -1,51 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload'
import { assertCliConversationWritersExited } from './structured-agent-cli-writers'
const row: AgentStatusIpcPayload = {
paneKey: 'source',
worktreeId: 'workspace',
connectionId: null,
agentType: 'claude',
receivedAt: 1,
stateStartedAt: 1,
state: 'done',
prompt: '',
providerSession: { key: 'session_id', id: 'conversation' }
}
const conflict = {
refusal: { code: 'agent_session_conflict', details: { reason: 'conversationHeldElsewhere' } }
}
describe('canonical status store conversation admission', () => {
// The source terminal's own agent stops with the close that follows, so it is no other writer.
it('leaves out the panes the caller closes, by key or by their PTY, unless a shared server holds it', async () => {
const ptys: Record<string, string> = { 'tab-1:leaf': 'pty-1', 'legacy-1': 'pty-1' }
const admit = (
rows: AgentStatusIpcPayload[],
topology: 'pane-owned' | 'shared' = 'pane-owned'
) =>
assertCliConversationWritersExited(
{
rows: () => rows,
observation: () => ({ current: () => true, presence: async () => 'live', topology }),
ptyResolver: () => (paneKey) => ptys[paneKey] ?? null
},
'claude',
'conversation',
['tab-1:leaf']
)
await expect(admit([{ ...row, paneKey: 'tab-1:leaf' }])).resolves.toBeUndefined()
await expect(admit([{ ...row, paneKey: 'legacy-1' }])).resolves.toBeUndefined()
await expect(admit([{ ...row, paneKey: 'tab-2:leaf' }])).rejects.toMatchObject(conflict)
await expect(admit([{ ...row, paneKey: 'tab-1:leaf' }], 'shared')).rejects.toMatchObject(
conflict
)
})
// Many terminals can name one conversation: a check starts only a few probes at once, and none
// once a holder refused.
// Every create, resume and acquire runs this check: resolving panes for nothing to leave out, or
// scanning every terminal for each row, would grow with rows times terminals.
})
@@ -1,70 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { RelayAssignRateGate } from './relay-assign-rate-gate'
import { requestRelayAssignment } from './relay-http-client'
type AssignInput = Parameters<typeof requestRelayAssignment>[0]
function assignSuccessResponse(): Response {
return Response.json({
v: 1,
cellUrl: 'https://relay-c1.example',
assignmentEpoch: 4,
lease: 'lease-jwt'
})
}
function fakeAssignClock(onSleep?: () => void) {
let now = 1_000_000
const sleeps: number[] = []
return {
sleeps,
advance: (ms: number): void => {
now += ms
},
options: {
now: () => now,
random: () => 0,
sleep: async (ms: number): Promise<void> => {
sleeps.push(ms)
now += ms
onSleep?.()
}
}
}
}
describe('relay assignment rate gate', () => {
const request = (
input: Partial<AssignInput> & Pick<AssignInput, 'fetch' | 'assignRateGate'>
): Promise<unknown> =>
requestRelayAssignment({
directorUrl: 'https://relay.example',
relayToken: 'scoped-token',
relayHostId: 'AbCdEf0123_-xyZ9',
...input
})
it('keeps a Retry-After hint past the retry timer the coordinator cancels', async () => {
const clock = fakeAssignClock()
const assignRateGate = new RelayAssignRateGate(clock.options)
const fetch = vi
.fn<typeof globalThis.fetch>()
.mockResolvedValueOnce(new Response(null, { status: 429, headers: { 'retry-after': '30' } }))
.mockResolvedValueOnce(assignSuccessResponse())
await expect(request({ fetch, assignRateGate })).rejects.toThrow('relay_assignment_failed_429')
// Reconcile resets retry timers; the gate must retain long Retry-After and fail inline with the remainder.
clock.advance(6_000)
await expect(request({ fetch, assignRateGate })).rejects.toMatchObject({
statusCode: 429,
retryAfterMs: 24_000
})
expect(clock.sleeps).toEqual([])
expect(fetch).toHaveBeenCalledTimes(1)
clock.advance(25_000)
await request({ fetch, assignRateGate })
expect(fetch).toHaveBeenCalledTimes(2)
})
})
@@ -1,56 +0,0 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import Database from '../../../../sqlite/sync-database'
import { dropDerivedDeliverySchema } from '../schema/derived-delivery-test-fixture'
import { OrchestrationDb } from '../orchestration-db'
import { SCHEMA_VERSION } from '../contract-constants'
import '../messages/mailbox-routing-page'
import '../dispatch-row-writer'
import '../attempt-outcome-projection'
import { resolveOrchestrationMigrationStartVersion } from '../schema/orchestration-schema-version-skew'
describe('federation acknowledgment migration', () => {
let db: OrchestrationDb | undefined
let tempDir: string | undefined
afterEach(() => {
db?.close()
if (tempDir) {
rmSync(tempDir, { recursive: true, force: true })
}
})
it('adds a zeroed durable acknowledgment watermark to v26 dispatches', () => {
tempDir = mkdtempSync(join(tmpdir(), 'orca-federation-ack-migration-'))
const dbPath = join(tempDir, 'orchestration.db')
db = new OrchestrationDb(dbPath)
db.close()
db = undefined
const oldDb = new Database(dbPath)
dropDerivedDeliverySchema(oldDb)
oldDb.exec('ALTER TABLE federated_dispatches DROP COLUMN to_home_acknowledged_sequence')
oldDb.pragma('user_version = 26')
expect(resolveOrchestrationMigrationStartVersion(oldDb, 26, 28)).toBe(26)
oldDb
.prepare(
`INSERT INTO federated_dispatches (
dispatch_id, environment_id, environment_name, peer_fingerprint,
protocol_version, to_home_imported_sequence
) VALUES ('ctx_migrated', 'env', 'worker', 'peer', 3, 2)`
)
.run()
oldDb.close()
db = new OrchestrationDb(dbPath)
const sqlite = (db as unknown as { db: Database.Database }).db
expect(sqlite.pragma('user_version', { simple: true })).toBe(SCHEMA_VERSION)
expect(db.getFederatedDispatch('ctx_migrated')).toMatchObject({
to_home_imported_sequence: 2,
to_home_acknowledged_sequence: 0
})
})
})
@@ -1,45 +0,0 @@
import { describe, expect, it } from 'vitest'
import { OrchestrationDb } from '../orchestration-db'
import '../contract-constants'
import './mailbox-routing-page'
import '../dispatch-row-writer'
import '../attempt-outcome-projection'
describe('PTY mailbox reservation cleanup', () => {
it('uses a PTY lookup and preserves reservation settlement semantics', () => {
const db = new OrchestrationDb(':memory:')
try {
const seed = db.db.prepare(`INSERT INTO messages
(id, from_handle, to_handle, subject, read, pointer_enter_pending,
pointer_pty_id, pointer_process_incarnation, delivered_at)
VALUES (?, 'sender', 'recipient', 'test', ?, ?, ?, 'incarnation', ?)`)
db.db.exec('BEGIN')
for (let i = 0; i < 1000; i++) {
seed.run(`history-${i}`, 1, 0, null, null)
}
seed.run('reserved', 0, 1, 'target', '2026-01-01 00:00:00')
seed.run('written', 0, 2, 'target', null)
seed.run('entered', 0, 3, 'target', null)
seed.run('read', 1, 2, 'target', '2026-01-01 00:00:00')
seed.run('other', 0, 1, 'other-pty', null)
db.db.exec('COMMIT')
db.releasePendingMailboxPointerForPty('target')
const read = (id: string) => db.db.prepare('SELECT * FROM messages WHERE id = ?').get(id)
for (const id of ['reserved', 'written', 'entered', 'read']) {
expect(read(id)).toMatchObject({
pointer_enter_pending: 0,
pointer_pty_id: null,
pointer_process_incarnation: null
})
}
expect(read('reserved')).toMatchObject({ delivered_at: null, read: 0 })
expect(read('written')).toMatchObject({ delivered_at: expect.any(String), read: 0 })
expect(read('entered')).toMatchObject({ delivered_at: expect.any(String), read: 0 })
expect(read('read')).toMatchObject({ delivered_at: '2026-01-01 00:00:00', read: 1 })
expect(read('other')).toMatchObject({ pointer_enter_pending: 1, pointer_pty_id: 'other-pty' })
expect(read('history-0')).toMatchObject({ read: 1, delivered_at: null })
} finally {
db.close()
}
})
})
@@ -1,55 +0,0 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it, vi } from 'vitest'
import type * as SyncDatabaseModule from '../../../sqlite/sync-database'
import { MobileNotificationDismissalStore } from './mobile-notification-dismissal-store'
const failure = vi.hoisted(() => ({ remainingOpens: 0 }))
vi.mock('../../../sqlite/sync-database', async (original) => {
const actual = await original<typeof SyncDatabaseModule>()
class FailingOpen extends actual.default {
constructor(...args: ConstructorParameters<typeof actual.default>) {
if (failure.remainingOpens > 0) {
failure.remainingOpens -= 1
throw Object.assign(new Error('read failed'), { code: 'EIO' })
}
super(...args)
}
}
return { ...actual, default: FailingOpen }
})
it('keeps history it could not read and merges dismissals recorded meanwhile', async () => {
const dir = mkdtempSync(join(tmpdir(), 'push-comment-'))
const dismiss = (notificationId: string, notificationSeq: number) => ({
type: 'dismiss' as const,
notificationId,
notificationEpoch: 'epoch',
notificationSeq
})
try {
const store = new MobileNotificationDismissalStore(dir)
store.record(dismiss('old', 1))
await store.close()
// The startup read fails; close() retries it and saves what was recorded meanwhile.
failure.remainingOpens = 1
vi.spyOn(console, 'warn').mockImplementation(() => {})
const restarted = new MobileNotificationDismissalStore(dir)
expect(restarted.hasLiveDelivery('anything')).toBe(true)
restarted.record(dismiss('new', 2))
await restarted.close()
const recovered = new MobileNotificationDismissalStore(dir)
await recovered.close()
const shown = (notificationId: string) => ({
notificationId,
notificationEpoch: 'epoch',
notificationSeq: 1
})
expect(recovered.reconcile([shown('old'), shown('new')])).toEqual([shown('old'), shown('new')])
} finally {
vi.restoreAllMocks()
rmSync(dir, { recursive: true, force: true })
}
})
@@ -1,53 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import '../orca-runtime-tests/orca-runtime-test-lifecycle.spec'
import '../orca-runtime-tests/runtime-test-module-registration.spec'
import { OrcaRuntimeService } from '../orca-runtime'
import { listWorktrees } from '../../git/worktrees/catalog/worktree-scan-cache'
import {
TEST_REPO_ID,
TEST_REPO_PATH,
makeWorktreeInfo,
store
} from '../orca-runtime-tests/orca-runtime-test-fixtures.spec'
import type { Repo } from '../../../shared/repository/repo-types'
import type { RuntimeClientEvent } from '../../../shared/remote-runtime/session-graph/runtime-client-events'
const externalPath = '/tmp/elsewhere/external'
async function createScannedRuntime() {
let repo: Repo = { ...store.getRepos()[0], externalWorktreeVisibility: 'hide' }
const runtime = new OrcaRuntimeService({
...store,
getRepo: (id: string) => (id === repo.id ? repo : undefined),
getRepos: () => [repo],
updateRepo: (_target: Repo, updates: Partial<Repo>) => {
repo = { ...repo, ...updates }
return repo
}
})
vi.mocked(listWorktrees).mockClear()
vi.mocked(listWorktrees).mockResolvedValue([
makeWorktreeInfo(TEST_REPO_PATH),
makeWorktreeInfo(externalPath)
])
const events: RuntimeClientEvent[] = []
runtime.onClientEvent((event) => events.push(event))
const isExternalVisible = async () =>
(await runtime.listDetectedManagedWorktrees(`id:${TEST_REPO_ID}`)).worktrees.find(
(worktree) => worktree.path === externalPath
)?.visible
expect(await isExternalVisible()).toBe(false)
return { runtime, events, isExternalVisible }
}
describe('repo.update worktree refresh', () => {
it('re-lists a newly shown external worktree without rescanning Git', async () => {
const { runtime, events, isExternalVisible } = await createScannedRuntime()
await runtime.updateRepo(`id:${TEST_REPO_ID}`, { externalWorktreeVisibility: 'show' })
expect(events).toContainEqual({ type: 'worktreesChanged', repoId: TEST_REPO_ID })
expect(await isExternalVisible()).toBe(true)
expect(listWorktrees).toHaveBeenCalledTimes(1)
})
})
@@ -1,51 +0,0 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { createOrchestrationWorkerReleaseHarness } from '../testing/worker-release.test-support'
import { registerBoundPty } from '../../../../../orca-runtime-tests/bind-first-pane.test-fixture'
const h = createOrchestrationWorkerReleaseHarness()
beforeEach(() => h.setup())
afterEach(() => h.cleanup())
// Boot-wait Keep open must find custody written at terminal creation, or a later release closes a kept pane (#19337, #19608).
it('a phone Keep open during the boot wait keeps the pane and fences the later release', async () => {
const gate = h.deferred<unknown>()
vi.spyOn(h.runtime, 'waitForTerminal').mockReturnValue(gate.promise as never)
const task = h.db.createTask({ spec: 'mid-boot phone takeover', runId: h.activeRunId })
const start = h.call('orchestration.workerStart', {
task: task.id,
from: 'term_coord',
agent: 'codex'
})
await vi.waitFor(() => expect(h.runtime.waitForTerminal).toHaveBeenCalled())
const dispatchId = (
h.db.db.prepare("SELECT dispatch_id FROM worker_dispatches WHERE state = 'starting'").get() as {
dispatch_id: string
}
).dispatch_id
h.runtime.registerPreAllocatedHandleForPty('pty-worker', 'term_worker')
registerBoundPty(h.runtime, 'pty-worker', 'repo::worktree', null, {
tabId: 'tab_worker',
leafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
})
vi.mocked(h.runtime.getTerminalPaneKey).mockRestore()
await expect(
h.call('orchestration.workerKeepOpen', { terminal: 'term_worker', keep: true })
).resolves.toEqual({ autoClose: { kept: true } })
gate.resolve({
handle: 'term_worker',
condition: 'tui-idle',
satisfied: true,
status: 'running',
exitCode: null
})
await expect(start).resolves.toMatchObject({ state: 'ready' })
h.settle(task.id, dispatchId, 'succeeded')
await expect(
h.call('orchestration.workerRelease', { dispatch: dispatchId })
).resolves.toMatchObject({ state: 'retained', reason: 'user_kept', processAction: 'none' })
expect(h.runtime.closeTerminal).not.toHaveBeenCalled()
})
@@ -1,53 +0,0 @@
import '../../../../../shared/native-chat/every-agent-chat.test-fixture'
import { describe, expect, it, vi } from 'vitest'
import { RpcDispatcher } from '../../dispatcher'
import type { RpcRequest } from '../../core'
import type { OrcaRuntimeService } from '../../../orca-runtime'
import { WORKTREE_METHODS } from './worktree'
import '../../../../../shared/remote-runtime/protocol/protocol-version'
import '../../../../../shared/remote-runtime/protocol/worktree-runtime-capabilities'
import '../../../../../shared/remote-runtime/protocol/electron-remote-runtime-client-capabilities'
describe('worktree.rm host qualification', () => {
function makeRuntime(repoHostIds: (string | undefined)[] = ['local']): OrcaRuntimeService {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this fixture supplies every runtime member reached by the requests in this suite.
return {
getRuntimeId: () => 'test-runtime',
listRepos: () =>
repoHostIds.map((executionHostId) => ({
id: 'repo-1',
path: '/repo',
executionHostId
})),
showManagedWorktree: vi.fn().mockResolvedValue({ id: 'wt-1', hostId: 'local' }),
removeManagedWorktree: vi.fn().mockResolvedValue({})
} as unknown as OrcaRuntimeService
}
const WORKTREE_ID = 'repo-1::/repo/wt'
function makeRequest(params: unknown): RpcRequest {
return { id: 'req-1', authToken: 'tok', method: 'worktree.rm', params }
}
it('fails closed when the repo id carries both spellings', async () => {
const runtime = makeRuntime(['local', 'runtime:env-1'])
const dispatcher = new RpcDispatcher({ runtime, methods: WORKTREE_METHODS })
const response = await dispatcher.dispatch(
makeRequest({
worktree: `id:${WORKTREE_ID}`,
hostId: 'runtime:env-1',
force: true,
runHooks: false
})
)
expect(response).toMatchObject({
ok: false,
error: { message: expect.stringContaining('ambiguous across hosts') }
})
expect(runtime.removeManagedWorktree).not.toHaveBeenCalled()
})
})
@@ -1,65 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { SidebarClock } from './sidebar-clock'
describe('SidebarClock', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(0)
})
afterEach(() => {
vi.useRealTimers()
})
it('arms one timer for the earliest of every pending deadline', () => {
const clock = new SidebarClock()
const fired: string[] = []
clock.schedule('late', 300, () => fired.push('late'))
clock.schedule('early', 100, () => fired.push('early'))
clock.schedule('mid', 200, () => fired.push('mid'))
expect(vi.getTimerCount()).toBe(1)
vi.advanceTimersByTime(100)
expect(fired).toEqual(['early'])
expect(vi.getTimerCount()).toBe(1)
vi.advanceTimersByTime(200)
expect(fired).toEqual(['early', 'mid', 'late'])
expect(vi.getTimerCount()).toBe(0)
})
it('replaces a key, cancels it, and lets a fire schedule its next deadline', () => {
const clock = new SidebarClock()
const fired: number[] = []
clock.schedule('a', 100, () => fired.push(1))
clock.schedule('a', 50, () => fired.push(2))
vi.advanceTimersByTime(60)
expect(fired).toEqual([2])
clock.schedule('b', 500, () => fired.push(3))
clock.cancel('b')
expect(vi.getTimerCount()).toBe(0)
const tick = (): void => {
fired.push(4)
if (fired.filter((n) => n === 4).length < 3) {
clock.schedule('tick', Date.now() + 10, tick)
}
}
clock.schedule('tick', Date.now() + 10, tick)
vi.advanceTimersByTime(100)
expect(fired.filter((n) => n === 4)).toHaveLength(3)
expect(vi.getTimerCount()).toBe(0)
})
it('keeps firing the rest when one deadline throws', () => {
const clock = new SidebarClock()
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
const fired: string[] = []
clock.schedule('bad', 10, () => {
throw new Error('boom')
})
clock.schedule('good', 10, () => fired.push('good'))
vi.advanceTimersByTime(10)
expect(fired).toEqual(['good'])
expect(error).toHaveBeenCalledOnce()
error.mockRestore()
})
})
@@ -1,59 +0,0 @@
/** Delete the emulator map entry before disposal so new writes create a fresh emulator.
* Chain disposal after all queued parses; reversing either order silently loses output. */
import { afterEach, describe, expect, it, vi } from 'vitest'
import { OrcaRuntimeService } from '../../orca-runtime'
const store = {
getRepo: () => undefined,
getRepos: () => [],
addRepo: () => {},
updateRepo: () => undefined as never,
getAllWorktreeMeta: () => ({}),
getWorktreeMeta: () => undefined,
setWorktreeMeta: () => undefined as never,
removeWorktreeMeta: () => {},
getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }),
addRetiredWorktreeName: () => {},
mergeRetiredWorktreeNames: () => false,
getGitHubCache: () => ({ pr: {}, issue: {} }) as never,
getSettings: () => ({
workspaceDir: '/tmp/workspaces',
nestWorkspaces: false,
refreshLocalBaseRefOnWorktreeCreate: false,
branchPrefix: 'none',
branchPrefixCustom: '',
terminalMainSideEffectAuthority: true
})
}
const PTY_ID = 'pty-dispose-ordering'
function createRuntime(): OrcaRuntimeService {
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
write: () => true,
kill: () => true,
getForegroundProcess: async () => null,
getSize: () => ({ cols: 80, rows: 24 }),
resize: () => true
})
return runtime
}
describe('disposeHeadlessTerminal write ordering', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('leaves the post-disposal emulator holding only post-disposal output', async () => {
const runtime = createRuntime()
runtime.onPtyData(PTY_ID, 'QUEUED-BEFORE-DISPOSE\r\n', 1)
runtime.preparePtyExecutionContext(PTY_ID, null, { resetIncarnation: true })
runtime.onPtyData(PTY_ID, 'ISSUED-AFTER-DISPOSE\r\n', 2)
const snapshot = await runtime.serializeHiddenOutputRecoveryBuffer(PTY_ID)
const painted = `${snapshot?.scrollbackAnsi ?? ''}${snapshot?.data ?? ''}`
expect(painted).toContain('ISSUED-AFTER-DISPOSE')
expect(painted).not.toContain('QUEUED-BEFORE-DISPOSE')
})
})
@@ -1,53 +0,0 @@
import type * as NodeFs from 'node:fs'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { getSystemCliInstallDirectories } from '../../shared/shell/command-resolution/system-cli-install-dirs'
import { patchPackagedProcessPath } from './configure-process'
const fsFixture = vi.hoisted(() => ({ macPortsInstalled: false }))
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof NodeFs>()
return {
...actual,
existsSync: (path: string) =>
path === '/opt/local/bin/port' ? fsFixture.macPortsInstalled : actual.existsSync(path)
}
})
vi.mock('electron', () => ({ app: { isPackaged: true } }))
describe('patchPackagedProcessPath MacPorts seed', () => {
const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
function seedDarwinPath(): string[] {
vi.stubEnv('HOME', '/Users/tester')
vi.stubEnv('PATH', '/usr/bin:/bin')
patchPackagedProcessPath()
return (process.env.PATH ?? '').split(':')
}
afterEach(() => {
fsFixture.macPortsInstalled = false
vi.unstubAllEnvs()
if (originalPlatform) {
Object.defineProperty(process, 'platform', originalPlatform)
}
})
it('seeds /opt/local last only when default-prefix port exists', () => {
Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' })
const withoutMacPorts = seedDarwinPath()
expect(withoutMacPorts).not.toContain('/opt/local/bin')
fsFixture.macPortsInstalled = true
const segments = seedDarwinPath()
// Appending only, so no existing binary resolves differently once MacPorts is installed.
expect(segments).toEqual([...withoutMacPorts, '/opt/local/bin', '/opt/local/sbin'])
// Lookup fallback must resolve a CLI in two system dirs the same way the seeded PATH does.
const offsets = getSystemCliInstallDirectories('darwin', '/Users/tester').map((directory) =>
segments.indexOf(directory)
)
expect(offsets.every((offset) => offset >= 0)).toBe(true)
expect([...offsets].sort((a, b) => a - b)).toEqual(offsets)
})
})
@@ -1,55 +0,0 @@
import { expect, it } from 'vitest'
import { createUsageEventAggregation } from './usage-event-aggregation'
import type { UsageAttributedEventFields } from './usage-rollup-records'
type Event = UsageAttributedEventFields & { cost: number }
const aggregation = createUsageEventAggregation<Event, { cost: number }>({
metric: {
empty: () => ({ cost: 0 }),
fromEvent: (event) => ({ cost: event.cost }),
fold: (target, source) => {
target.cost += source.cost
}
},
cloneSessionForMerge: (session) => structuredClone(session)
})
function events(count: number): Event[] {
return Array.from({ length: count }, (_, index) => ({
sessionId: 'session',
timestamp: '2026-09-07T00:00:00Z',
day: '2026-09-07',
model: `model-${index % 5}`,
projectKey: `path-${index}`,
projectLabel: `Path ${index}`,
repoId: null,
worktreeId: null,
inputTokens: 1,
cachedInputTokens: 0,
outputTokens: 2,
reasoningOutputTokens: 0,
totalTokens: 3,
cost: 0.5
}))
}
// Index newly appended rows too or later sources append duplicate location/model entries.
it('folds later sources into rows the merge itself appended', () => {
const [first] = events(1)
first.projectKey = 'new-location'
first.projectLabel = 'New location'
first.model = 'new-model'
const incoming = aggregation.aggregate([first]).sessions[0]
const existingOnly = events(1)
existingOnly[0].projectKey = 'other'
const existing = aggregation.aggregate(existingOnly).sessions[0]
aggregation.mergeSessions(new Map([['session', existing]]), [incoming, structuredClone(incoming)])
const rows = existing.locationBreakdown.filter((entry) => entry.locationKey === 'new-location')
expect(rows.map((entry) => entry.eventCount)).toEqual([2])
const models = existing.modelBreakdown.filter((entry) => entry.modelKey === 'new-model')
expect(models.map((entry) => entry.eventCount)).toEqual([2])
const tuples = existing.locationModelBreakdown.filter(
(entry) => entry.locationKey === 'new-location' && entry.modelKey === 'new-model'
)
expect(tuples.map((entry) => entry.eventCount)).toEqual([2])
})
@@ -1,182 +0,0 @@
// @vitest-environment happy-dom
// Use stable browser page IDs for tools and annotations; re-mint replaces the guest without renaming its surface.
import { act, createElement, useRef } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { BrowserGrabPayload } from '../../../../../shared/browser/element-grab/browser-grab-types'
import { BROWSER_ANNOTATION_VIEWPORT_MESSAGE_PREFIX } from '../../../../../shared/browser/annotations/browser-annotation-viewport-bridge'
import { makeAnnotation } from '@/store/slices/browser/annotations/browser-annotation-test-fixture'
import { getBrowserOverlayAnchor } from '../describe-page/browser-annotation-geometry'
import { attachDocPreviewWebview } from './doc-preview-webview-attach'
type GuestToolCalls = {
annotationSend: { browserTabId: string }[]
grabAnnotations: { browserTabId: string; toolTargetId: string }[]
grabMode: string[]
viewportBridge: { toolTargetId: string; token: string }[]
}
const calls = vi.hoisted<GuestToolCalls>(() => ({
annotationSend: [],
grabAnnotations: [],
grabMode: [],
viewportBridge: []
}))
let pendingPayload: BrowserGrabPayload | null = null
vi.mock('@/components/browser-pane/annotate/delivery/use-browser-page-annotation-send', () => ({
useBrowserPageAnnotationSend: (args: { browserTabId: string }) => {
calls.annotationSend.push({ browserTabId: args.browserTabId })
return { browserAnnotations: [] }
}
}))
vi.mock('@/components/browser-pane/annotate/grab/use-browser-page-grab-annotations', () => ({
useBrowserPageGrabAnnotations: (args: { browserTabId: string; toolTargetId: string }) => {
calls.grabAnnotations.push({
browserTabId: args.browserTabId,
toolTargetId: args.toolTargetId
})
return {
pendingAnnotationPayload: pendingPayload,
grabIntent: null,
startGrabIntent: () => undefined
}
}
}))
vi.mock('@/components/browser-pane/annotate/capture/use-browser-page-markup-capture', () => ({
useBrowserPageMarkupCapture: () => ({ isActive: false })
}))
vi.mock('@/components/browser-pane/annotate/grab/useGrabMode', () => ({
useGrabMode: (toolTargetId: string) => {
calls.grabMode.push(toolTargetId)
return { state: 'idle' }
}
}))
vi.mock('@/components/browser-pane/annotate/viewport/guest-annotation-viewport-bridge', () => ({
syncGuestAnnotationViewportBridge: (args: { toolTargetId: string; token: string }) => {
calls.viewportBridge.push({ toolTargetId: args.toolTargetId, token: args.token })
}
}))
vi.mock('@/hooks/useShortcutLabel', () => ({ useShortcutLabel: () => 'G' }))
import { useDocPreviewGuestTools } from './use-doc-preview-guest-tools'
const PREVIEW_ID = 'browser-page-9f2c'
const FIRST_GRANT = 'a'.repeat(32)
function Harness({ grantId }: { grantId: string | null }): null {
const webviewRef = useRef(null)
const containerRef = useRef(null)
latestTools = useDocPreviewGuestTools({
previewId: PREVIEW_ID,
worktreeId: 'wt-1',
grantId,
webviewRef: webviewRef as never,
containerRef: containerRef as never,
toolsReady: true
})
return null
}
let container: HTMLDivElement
let root: Root
let latestTools: ReturnType<typeof useDocPreviewGuestTools> | null = null
function currentTools(): ReturnType<typeof useDocPreviewGuestTools> {
if (!latestTools) {
throw new Error('preview tools not rendered')
}
return latestTools
}
function render(grantId: string | null): void {
act(() => {
root.render(createElement(Harness, { grantId }))
})
}
beforeEach(() => {
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
calls.annotationSend.length = 0
calls.grabAnnotations.length = 0
calls.grabMode.length = 0
calls.viewportBridge.length = 0
pendingPayload = null
latestTools = null
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
})
afterEach(() => {
act(() => root.unmount())
container.remove()
vi.unstubAllGlobals()
})
describe('useDocPreviewGuestTools ids', () => {
it('moves the pending card from a live report after inner scroll and removes the listener on detach', () => {
const selected = makeAnnotation(PREVIEW_ID).payload
selected.page.viewportWidth = 900
selected.target.rectPage = { x: 40, y: 300, width: 120, height: 30 }
selected.target.rectViewport = { x: 40, y: 300, width: 120, height: 30 }
pendingPayload = selected
render(FIRST_GRANT)
const token = calls.viewportBridge.at(-1)?.token
expect(token).toBeTruthy()
const previewContainer = document.createElement('div')
document.body.appendChild(previewContainer)
const attached = attachDocPreviewWebview({
previewId: PREVIEW_ID,
container: previewContainer,
url: 'orca-preview://grant/index.html',
ariaLabel: 'HTML preview',
onLoadStarted: () => currentTools().resetBrowserOverlayViewport(),
onLoadStopped: vi.fn(),
onLoadFailed: vi.fn(),
onNavigated: vi.fn(),
onTitleUpdated: vi.fn(),
onViewportMessage: currentTools().handleAnnotationViewportMessage
})
const pane = {
getBoundingClientRect: () => ({ left: 0, top: 0, width: 900, height: 900 })
}
const cardY = (): number =>
getBrowserOverlayAnchor(selected, pane, pane, currentTools().browserOverlayViewport).y
const send = (message: string): void => {
act(() => {
attached.webview.dispatchEvent(Object.assign(new Event('console-message'), { message }))
})
}
try {
expect(cardY()).toBe(330)
const report = JSON.stringify({
scrollX: 0,
scrollY: 0,
viewportWidth: 900,
target: { x: 40, y: 120, width: 120, height: 30 }
})
send(`${BROWSER_ANNOTATION_VIEWPORT_MESSAGE_PREFIX}wrong-token:${report}`)
expect(cardY()).toBe(330)
send(`${BROWSER_ANNOTATION_VIEWPORT_MESSAGE_PREFIX}${token}:${report}`)
expect(cardY()).toBe(150)
act(() => attached.webview.dispatchEvent(new Event('did-start-loading')))
expect(cardY()).toBe(330)
attached.detach()
send(`${BROWSER_ANNOTATION_VIEWPORT_MESSAGE_PREFIX}${token}:${report}`)
expect(cardY()).toBe(330)
} finally {
attached.detach()
previewContainer.remove()
}
})
})
@@ -1,194 +0,0 @@
import { acceptedAgentStatuses } from '@/store/slices/agent-status/accepted-agent-statuses'
// @vitest-environment happy-dom
import { act, createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { NativeChatMessage } from '../../../../../../../shared/native-chat/native-chat-types'
import { useAppStore } from '@/store'
const { resetTransport, subscriptions, transport } = vi.hoisted(() => {
const subscriptions: { onFrame: (frame: unknown) => void }[] = []
const transport = { readSession: vi.fn(), subscribe: vi.fn() }
const resetTransport = (): void => {
subscriptions.splice(0)
// Hold the seed in flight so only emitted frames move the view.
transport.readSession.mockReset().mockImplementation(() => new Promise(() => {}))
transport.subscribe.mockReset().mockImplementation((_args, onFrame) => {
subscriptions.push({ onFrame })
return vi.fn()
})
}
return { resetTransport, subscriptions, transport }
})
vi.mock('./native-chat-session-transport', () => ({
getNativeChatSessionTransport: () => transport
}))
import { NOTFOUND_RETRY_WINDOW_MS, useNativeChatLiveSession } from './use-native-chat-live-session'
import type {
UseNativeChatLiveSessionArgs,
NativeChatLiveSession
} from './native-chat-live-session-contract'
import { useNativeChatRetainedSession } from './use-native-chat-retained-session'
const BASE_ARGS: UseNativeChatLiveSessionArgs = {
paneKey: 'tab-1:leaf-1',
agent: 'claude',
sessionId: 'session-1',
transcriptPath: '/home/agent/session-1.jsonl',
enabled: true
}
const PENDING_FRAME = { type: 'snapshot', messages: [], hasMore: false, pending: true }
function assistant(id: string): NativeChatMessage {
return {
id,
role: 'assistant',
blocks: [{ type: 'text', text: id }],
timestamp: 1,
source: 'transcript'
}
}
describe('useNativeChatLiveSession — unflushed transcript (pending frame)', () => {
let root: Root
let latest: NativeChatLiveSession | null = null
function Probe(props: UseNativeChatLiveSessionArgs): null {
latest = useNativeChatLiveSession(props)
return null
}
async function render(props: UseNativeChatLiveSessionArgs = BASE_ARGS): Promise<void> {
await act(async () => {
root.render(createElement(Probe, props))
await Promise.resolve()
await Promise.resolve()
})
}
async function emit(frame: unknown): Promise<void> {
await act(async () => {
subscriptions[0]?.onFrame(frame)
await Promise.resolve()
})
}
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
root = createRoot(document.createElement('div'))
latest = null
resetTransport()
useAppStore.setState({ agentStatusByPaneKey: acceptedAgentStatuses(Object.entries({})) })
})
afterEach(() => {
act(() => root.unmount())
vi.useRealTimers()
})
it('keeps the readSession seed live, so the real transcript still backfills', async () => {
// A flush between stream drains needs the independent seed; pending frames must leave it eligible.
let settleRead = (_result: { messages: NativeChatMessage[] }): void => {}
transport.readSession.mockImplementationOnce(
() => new Promise((resolve) => (settleRead = resolve))
)
await render()
await emit(PENDING_FRAME)
await act(async () => {
settleRead({ messages: [assistant('flushed-later')] })
await Promise.resolve()
})
expect(latest?.readPhase).toBe('ready')
expect(latest?.messages.map((message) => message.id)).toEqual(['flushed-later'])
})
it('settles to ready when the real snapshot arrives on the same subscription', async () => {
await render()
await emit(PENDING_FRAME)
await emit({ type: 'snapshot', messages: [assistant('m-1')], hasMore: false })
expect(latest?.readPhase).toBe('ready')
expect(latest?.messages.map((message) => message.id)).toEqual(['m-1'])
})
it('stops duplicate seed polling once the live stream owns the pending transcript', async () => {
vi.useFakeTimers()
let settleRead = (_result: { error: string; notFound: true }): void => {}
transport.readSession.mockImplementationOnce(
() => new Promise((resolve) => (settleRead = resolve))
)
await render()
await emit(PENDING_FRAME)
await act(async () => {
settleRead({ error: 'no transcript', notFound: true })
await Promise.resolve()
await vi.advanceTimersByTimeAsync(NOTFOUND_RETRY_WINDOW_MS + 30_000)
})
expect(latest?.readPhase).toBe('awaiting')
expect(latest?.status).not.toBe('error')
expect(transport.readSession).toHaveBeenCalledOnce()
})
it('does not drop live appends already merged into the window', async () => {
await render()
await emit({ type: 'appended', messages: [assistant('appended-1')] })
await emit(PENDING_FRAME)
expect(latest?.readPhase).toBe('awaiting')
expect(latest?.messages.map((message) => message.id)).toEqual(['appended-1'])
})
})
describe('useNativeChatRetainedSession — unflushed transcript', () => {
let root: Root
let latest: NativeChatLiveSession | null = null
function Probe(props: UseNativeChatLiveSessionArgs): null {
latest = useNativeChatRetainedSession(props)
return null
}
async function emit(frame: unknown): Promise<void> {
await act(async () => {
subscriptions[0]?.onFrame(frame)
await Promise.resolve()
})
}
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
root = createRoot(document.createElement('div'))
latest = null
resetTransport()
useAppStore.setState({ agentStatusByPaneKey: acceptedAgentStatuses(Object.entries({})) })
})
afterEach(() => {
act(() => root.unmount())
})
it('retains committed history instead of capturing the empty pending window', async () => {
await act(async () => {
root.render(createElement(Probe, BASE_ARGS))
await Promise.resolve()
await Promise.resolve()
})
await emit({ type: 'snapshot', messages: [assistant('committed')], hasMore: false })
await emit(PENDING_FRAME)
expect(latest?.readPhase).toBe('awaiting')
expect(latest?.messages.map((message) => message.id)).toEqual(['committed'])
})
})
@@ -1,153 +0,0 @@
// @vitest-environment happy-dom
import { act, render, within } from '@testing-library/react'
import type { ReactNode } from 'react'
import { describe, expect, it, vi } from 'vitest'
import type { BrowserPage } from '../../../../../../shared/browser/workspaces/browser-workspace-types'
import type { NativeChatToolCallBlock } from '../../../../../../shared/native-chat/native-chat-types'
import { setBrowserAgentPageActive } from '../../../browser-pane/agent-cursor/browser-agent-activity-state'
import {
NativeChatVisualOwnerContext,
type NativeChatVisualOwner
} from '../../media/visuals/native-chat-visual-owner'
import { NativeChatBrowserRunPageButton } from './NativeChatBrowserPageButton'
function page(id: string, title: string): BrowserPage {
return {
id,
workspaceId: 'ws-1',
worktreeId: 'wt-1',
url: `https://example.com/${id}`,
title,
loading: false,
faviconUrl: null,
canGoBack: false,
canGoForward: false,
loadError: null,
createdAt: 1
}
}
const state = vi.hoisted((): { browserPagesByWorkspace: Record<string, BrowserPage[]> } => ({
browserPagesByWorkspace: {}
}))
vi.mock('@/store', () => ({
useAppStore: (select: (current: typeof state) => unknown) => select(state)
}))
const transcript = vi.hoisted(() => {
const listeners = new Set<() => void>()
let snapshot: { current: boolean; state: { items: unknown[] } } = {
current: true,
state: { items: [] }
}
return {
owner: {
getSnapshot: () => snapshot,
subscribe: (listener: () => void) => {
listeners.add(listener)
return () => listeners.delete(listener)
}
},
setCalls(calls: readonly NativeChatToolCallBlock[]) {
snapshot = {
current: true,
state: { items: calls.map((call) => ({ body: { ...call, kind: 'tool-call' } })) }
}
listeners.forEach((listener) => listener())
},
setCurrent(current: boolean) {
snapshot = { ...snapshot, current }
listeners.forEach((listener) => listener())
}
}
})
vi.mock('../../session/structured/read/structured-agent-session-read-owner-registry', () => ({
findStructuredAgentSessionReadOwner: () => transcript.owner
}))
const OWNER: NativeChatVisualOwner = {
target: { kind: 'local' },
sessionId: 'session-1',
worktreeId: 'wt-1'
}
function wrapper({ children }: { children: ReactNode }): React.JSX.Element {
return (
<NativeChatVisualOwnerContext.Provider value={OWNER}>
{children}
</NativeChatVisualOwnerContext.Provider>
)
}
function browserCall(callId: string, command = 'orca browser click @e1'): NativeChatToolCallBlock {
return { type: 'tool-call', name: 'Bash', input: { command }, callId }
}
function shownTitle(container: HTMLElement): string | null {
return within(container).queryByRole('button')?.getAttribute('title') ?? null
}
describe('NativeChatBrowserRunPageButton', () => {
it("keeps an older run's page after a newer run drives another page", () => {
state.browserPagesByWorkspace = { 'ws-1': [page('p1', 'First'), page('p2', 'Second')] }
const older = browserCall('run-a')
act(() => transcript.setCalls([older]))
const olderRun = render(<NativeChatBrowserRunPageButton calls={[older]} />, { wrapper })
act(() => setBrowserAgentPageActive('p1', true, 'wt-1', undefined, 'session-1'))
expect(shownTitle(olderRun.container)).toBe('First')
const newer = browserCall('run-b')
act(() => transcript.setCalls([older, newer]))
const newerRun = render(<NativeChatBrowserRunPageButton calls={[newer]} />, { wrapper })
act(() => setBrowserAgentPageActive('p2', true, 'wt-1', undefined, 'session-1'))
expect(shownTitle(olderRun.container)).toBe('First')
expect(shownTitle(newerRun.container)).toBe('Second')
})
it('ignores other agents driving a different page', () => {
state.browserPagesByWorkspace = { 'ws-1': [page('p1', 'Mine'), page('p2', 'Theirs')] }
const call = browserCall('run-c')
act(() => transcript.setCalls([call]))
setBrowserAgentPageActive('p1', true, 'wt-1', undefined, 'session-1')
const { container } = render(<NativeChatBrowserRunPageButton calls={[call]} />, { wrapper })
act(() => setBrowserAgentPageActive('p2', true, 'wt-1'))
act(() => setBrowserAgentPageActive('p2', true, 'wt-1', undefined, 'session-2'))
expect(shownTitle(container)).toBe('Mine')
})
it('shows the page for the newest run even when its activity arrived before the run drew', () => {
state.browserPagesByWorkspace = { 'ws-1': [page('p1', 'Driven')] }
const call = browserCall('run-d')
setBrowserAgentPageActive('p1', true, 'wt-1', undefined, 'session-1')
act(() => transcript.setCalls([call]))
const { container } = render(<NativeChatBrowserRunPageButton calls={[call]} />, { wrapper })
expect(shownTitle(container)).toBe('Driven')
})
it("never shows another run's page for an older run whose page this renderer never saw", () => {
state.browserPagesByWorkspace = { 'ws-1': [page('p1', 'Older'), page('p2', 'Newer')] }
const older = browserCall('run-restored')
const newer = browserCall('run-newest')
act(() => transcript.setCalls([older, newer]))
setBrowserAgentPageActive('p1', true, 'wt-1', undefined, 'session-1')
const { container } = render(<NativeChatBrowserRunPageButton calls={[older]} />, { wrapper })
expect(shownTitle(container)).toBeNull()
act(() => setBrowserAgentPageActive('p2', true, 'wt-1', undefined, 'session-1'))
expect(shownTitle(container)).toBeNull()
})
it('keeps a run off a newer page while the transcript is behind the agent', () => {
state.browserPagesByWorkspace = { 'ws-1': [page('p1', 'Mine'), page('p2', 'Unseen run')] }
const call = browserCall('run-e')
act(() => transcript.setCalls([call]))
const { container } = render(<NativeChatBrowserRunPageButton calls={[call]} />, { wrapper })
act(() => setBrowserAgentPageActive('p1', true, 'wt-1', undefined, 'session-1'))
act(() => transcript.setCurrent(false))
act(() => setBrowserAgentPageActive('p2', true, 'wt-1', undefined, 'session-1'))
expect(shownTitle(container)).toBe('Mine')
})
})
@@ -1,179 +0,0 @@
// @vitest-environment happy-dom
import { act, cleanup, fireEvent, render } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { TooltipProvider } from '@/components/ui/tooltip'
import type { AiVaultSession } from '../../../../../../shared/ai-vault/contracts/ai-vault-types'
import { AiVaultSessionVirtualList } from './AiVaultSessionVirtualList'
function makeSession(index: number): AiVaultSession {
return {
id: `local:omp:session-${index}:/tmp/session-${index}.jsonl`,
executionHostId: 'local',
agent: 'omp',
sessionId: `session-${index}`,
title: `Session ${index}`,
cwd: '/repo',
branch: null,
model: 'gpt-5',
filePath: `/tmp/session-${index}.jsonl`,
codexHome: null,
createdAt: null,
updatedAt: null,
modifiedAt: '2026-09-17T00:00:00.000Z',
messageCount: 10,
totalTokens: 0,
previewMessages: [{ role: 'assistant', text: `Reply ${index}`, timestamp: null }],
queuedMessageCount: 0,
subagentTranscriptCount: 0,
resumeCommand: `omp resume session-${index}`,
subagent: null
}
}
afterEach(() => {
cleanup()
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
function renderList(sessions: AiVaultSession[], loading = false) {
return render(
<TooltipProvider>
<AiVaultSessionVirtualList
groups={[{ key: 'live_studio_mono', label: 'live_studio_mono', sessions }]}
collapsedGroups={new Set()}
loading={loading}
sessionsCount={sessions.length}
filteredSessionsCount={sessions.length}
noAgentsSelected={false}
error={null}
vaultScope="workspace"
buildResumeStartup={(session) => ({ command: session.resumeCommand })}
getOriginalPaneTarget={() => null}
isStructuredSessionOpen={() => false}
getSessionLiveState={() => null}
getWorktreeInfo={() => null}
getSessionResumeState={() => ({
blocked: false,
worktreeId: 'worktree-1',
usesSessionWorktree: false
})}
getSessionResumeActions={() => ({
worktree: { worktreeId: null, disabled: true },
newTab: { worktreeId: 'worktree-1', disabled: false }
})}
getSessionResumeInChat={() => ({ available: false, reason: 'already-structured' })}
onToggleGroup={vi.fn()}
onJumpToOriginalPane={vi.fn()}
onJumpToWorktree={vi.fn()}
onResume={vi.fn()}
onContinueInNewSession={vi.fn()}
onResumeInNewChat={vi.fn()}
onResumeInNewCli={vi.fn()}
onCopyResume={vi.fn()}
onCopyId={vi.fn()}
onCopyPath={vi.fn()}
onOpenLog={vi.fn()}
onRevealLog={vi.fn()}
onOpenCwd={vi.fn()}
onRevealArtifacts={vi.fn()}
onRequestDelete={vi.fn()}
/>
</TooltipProvider>
)
}
describe('AiVaultSessionVirtualList row measurement', () => {
it('keeps measured offsets while hidden and accepts positive sizes after restore', () => {
const observers = new Map<
ResizeObserver,
{
callback: ResizeObserverCallback
targets: Set<Element>
}
>()
class TestResizeObserver implements ResizeObserver {
constructor(callback: ResizeObserverCallback) {
observers.set(this, { callback, targets: new Set() })
}
observe(target: Element): void {
observers.get(this)?.targets.add(target)
}
unobserve(target: Element): void {
observers.get(this)?.targets.delete(target)
}
disconnect(): void {
observers.delete(this)
}
}
vi.stubGlobal('ResizeObserver', TestResizeObserver)
vi.stubGlobal('api', { aiVault: {} })
vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation(function (
this: HTMLElement
) {
if (this.classList.contains('overflow-y-auto')) {
return 600
}
return this.getAttribute('data-index') === '0' ? 32 : 98
})
const { container, getByText } = renderList([makeSession(1), makeSession(2), makeSession(3)])
const first = container.querySelector<HTMLElement>('[data-index="1"]')
const second = container.querySelector<HTMLElement>('[data-index="2"]')
if (!first || !second) {
throw new Error('Expected session rows to render')
}
const resize = (element: Element, height: number): void => {
act(() => {
for (const [observer, { callback, targets }] of observers) {
if (!targets.has(element)) {
continue
}
const size = [{ blockSize: height, inlineSize: 440 }]
callback(
[
{
target: element,
borderBoxSize: size,
contentBoxSize: size,
devicePixelContentBoxSize: size,
contentRect: element.getBoundingClientRect()
}
],
observer
)
}
})
}
expect(second.style.transform).toBe('translateY(130px)')
resize(first, 117)
expect(second.style.transform).toBe('translateY(149px)')
fireEvent.click(getByText('Session 1'))
resize(first, 669)
expect(second.style.transform).toBe('translateY(701px)')
const scroller = container.querySelector<HTMLElement>('.overflow-y-auto')
if (!scroller) {
throw new Error('Expected scroll viewport')
}
const hiddenRects = scroller.getClientRects()
Array.prototype.splice.call(hiddenRects, 0, hiddenRects.length)
const layoutBox = vi.spyOn(scroller, 'getClientRects').mockReturnValue(hiddenRects)
resize(first, 0)
expect(second.style.transform).toBe('translateY(701px)')
layoutBox.mockRestore()
resize(first, 720)
expect(second.style.transform).toBe('translateY(752px)')
fireEvent.click(getByText('Session 1'))
resize(first, 117)
expect(second.style.transform).toBe('translateY(149px)')
const collapsedLayoutBox = vi.spyOn(scroller, 'getClientRects').mockReturnValue(hiddenRects)
resize(first, 0)
expect(second.style.transform).toBe('translateY(149px)')
collapsedLayoutBox.mockRestore()
resize(first, 135)
expect(second.style.transform).toBe('translateY(167px)')
})
})
@@ -1,197 +0,0 @@
// @vitest-environment happy-dom
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { RemoteFileBrowser } from './RemoteFileBrowser'
const browseDir = vi.fn(async ({ dirPath }: { dirPath: string }) => ({
entries: [
{ name: 'docs', isDirectory: true },
{ name: 'src', isDirectory: true },
{ name: 'README.md', isDirectory: false }
],
resolvedPath: dirPath === '~' ? '/home/alice' : dirPath,
pathFlavor: 'posix' as const
}))
async function flushPromises(): Promise<void> {
for (let index = 0; index < 4; index += 1) {
await Promise.resolve()
}
}
async function render(): Promise<{
container: HTMLDivElement
input: HTMLInputElement
root: Root
}> {
const container = document.createElement('div')
document.body.appendChild(container)
const root = createRoot(container)
await act(async () => {
root.render(<RemoteFileBrowser targetId="target-1" onSelect={vi.fn()} onCancel={vi.fn()} />)
await flushPromises()
})
const input = container.querySelector('input')
if (!input) {
throw new Error('Remote file browser input was not rendered')
}
return { container, input, root }
}
async function press(
input: HTMLInputElement,
key: string,
modifiers: KeyboardEventInit = {}
): Promise<void> {
await act(async () => {
input.dispatchEvent(
new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true, ...modifiers })
)
await flushPromises()
})
}
async function type(input: HTMLInputElement, value: string): Promise<void> {
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set?.call(input, value)
input.dispatchEvent(new Event('input', { bubbles: true }))
})
}
async function settlePathResolve(): Promise<void> {
await act(async () => {
vi.advanceTimersByTime(300)
await flushPromises()
})
}
function selectedRow(container: HTMLElement): string | null | undefined {
return container.querySelector('[role="option"][aria-selected="true"]')?.textContent
}
describe('RemoteFileBrowser keyboard navigation', () => {
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
browseDir.mockClear()
Object.defineProperty(window, 'api', { configurable: true, value: { ssh: { browseDir } } })
})
afterEach(() => {
vi.useRealTimers()
document.body.replaceChildren()
vi.restoreAllMocks()
})
it('highlights the first row and moves it with the arrow keys', async () => {
const { container, input, root } = await render()
expect(selectedRow(container)).toBe('docs')
expect(input.getAttribute('aria-activedescendant')).toBe(
container.querySelector('[role="option"][aria-selected="true"]')?.id
)
expect(input.getAttribute('role')).toBe('combobox')
expect(input.getAttribute('aria-controls')).toBe(
container.querySelector('[role="listbox"]')?.id
)
await press(input, 'ArrowDown')
await press(input, 'ArrowDown')
await press(input, 'ArrowDown')
expect(selectedRow(container)).toBe('README.md')
await press(input, 'ArrowUp')
expect(selectedRow(container)).toBe('src')
// Modified arrows stay with the input (selection, caret jumps).
await press(input, 'ArrowDown', { shiftKey: true })
expect(selectedRow(container)).toBe('src')
await act(async () => root.unmount())
})
// Why: the previous listing's single folder would otherwise win Enter while the next one loads.
it('ignores Enter while the next listing loads', async () => {
browseDir.mockImplementationOnce(async () => ({
entries: [
{ name: 'docs', isDirectory: true },
{ name: 'README.md', isDirectory: false }
],
resolvedPath: '/home/alice',
pathFlavor: 'posix' as const
}))
const { input, root } = await render()
browseDir.mockClear()
browseDir.mockImplementationOnce(() => new Promise(() => {}))
await press(input, 'Enter')
await press(input, 'Enter')
expect(browseDir).toHaveBeenCalledTimes(1)
await act(async () => root.unmount())
})
// Why: the cached home listing comes back as the same array under `~/`, which must not keep the moved row.
it('commits a typed path instead of a row highlighted before typing it', async () => {
vi.useFakeTimers()
const { input, root } = await render()
await press(input, 'ArrowDown')
browseDir.mockClear()
await type(input, '~/')
await settlePathResolve()
await press(input, 'Enter')
// Committing `~/` reopens the cached home listing and clears the typed path.
expect(input.value).toBe('')
expect(browseDir).not.toHaveBeenCalledWith({
targetId: 'target-1',
dirPath: '/home/alice/src'
})
await act(async () => root.unmount())
})
// Why: until the debounce resolves `docs/`, the preview and its moved highlight still show `~/`.
it('ignores Enter on a typed directory that has not resolved yet', async () => {
vi.useFakeTimers()
const { input, root } = await render()
await type(input, '~/')
await settlePathResolve()
await press(input, 'ArrowDown')
await press(input, 'ArrowDown')
browseDir.mockClear()
await type(input, '~/docs/')
await press(input, 'Enter')
expect(browseDir).not.toHaveBeenCalled()
await settlePathResolve()
await press(input, 'Enter')
expect(browseDir).toHaveBeenLastCalledWith({
targetId: 'target-1',
dirPath: '/home/alice/docs'
})
await act(async () => root.unmount())
})
// Why: before the first preview, `.` still filters the old rows, so the default highlight is a dotfolder.
it('ignores Enter on path input that has no preview yet', async () => {
vi.useFakeTimers()
browseDir.mockImplementationOnce(async () => ({
entries: [
{ name: '.config', isDirectory: true },
{ name: '.ssh', isDirectory: true }
],
resolvedPath: '/home/alice',
pathFlavor: 'posix' as const
}))
const { input, root } = await render()
browseDir.mockClear()
await type(input, '.')
await press(input, 'Enter')
expect(browseDir).not.toHaveBeenCalled()
await act(async () => root.unmount())
})
})
@@ -1,174 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { RuntimeEditorTabReveal } from '../../../../shared/file-access/runtime-editor-file-open'
import { createTestStore, seedStore } from '../../store/testing/app-store-test-fixture'
import { makeWorktree } from '../../store/slices/worktrees/worktree.test-fixture'
import { createStoreSessionMockApi } from '../../store/testing/app-store-session-api.test-fixture'
import type * as HostPersistence from '@/lib/workspace/persistence/workspace-session-host-persistence'
import {
_resetLayoutFramePositionForTests,
beginLayoutFramePositions,
noteLayoutFramePosition
} from '@/runtime/workspace-layout/frames/layout-frame-position'
const { storeRef } = vi.hoisted(() => {
const ref: { current: ReturnType<typeof createTestStore> | null } = { current: null }
return { storeRef: ref }
})
function testStore(): ReturnType<typeof createTestStore> {
if (!storeRef.current) {
throw new Error('test store not created')
}
return storeRef.current
}
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
vi.mock('../../store', () => ({
useAppStore: {
getState: () => testStore().getState(),
subscribe: (...args: Parameters<ReturnType<typeof createTestStore>['subscribe']>) =>
testStore().subscribe(...args),
setState: (...args: Parameters<ReturnType<typeof createTestStore>['setState']>) =>
testStore().setState(...args)
}
}))
vi.mock('@/components/terminal-pane/layout/close/closed-terminal-leaf-notice', () => ({
applyClosedTerminalLeafNotice: vi.fn()
}))
vi.mock('@/components/terminal/terminal-tab-actions', () => ({ closeTerminalTab: vi.fn() }))
vi.mock('@/components/sidebar/workspace-actions/sleep/sleep-worktree-flow', () => ({
runSleepWorktree: vi.fn()
}))
vi.mock('@/lib/workspace/persistence/workspace-session', () => ({
buildWorkspaceSessionPayload: vi.fn()
}))
vi.mock(
'@/lib/workspace/persistence/workspace-session-host-persistence',
async (importOriginal) => ({
...(await importOriginal<typeof HostPersistence>()),
persistWorkspaceSessionByHost: vi.fn()
})
)
import { registerMobileAndTerminalCloseIpcBridge } from './mobile-terminal-close-ipc-bridge'
const WT = 'repo1::/repo1/wt'
const UNDRAWN = 'repo1::/repo1/undrawn'
const FILE = { filePath: '/repo1/wt/notes.md', relativePath: 'notes.md' }
function setup(): {
reveal: (payload: RuntimeEditorTabReveal) => void
tabId: string
activeTabId: () => string | null | undefined
activeWorktreeId: () => string | null
store: ReturnType<typeof createTestStore>
} {
let reveal: ((payload: RuntimeEditorTabReveal) => void) | undefined
const noop = (): (() => void) => () => {}
vi.stubGlobal('window', {
api: {
...createStoreSessionMockApi(),
ui: {
onOpenFileFromMobile: noop,
onOpenDiffFromMobile: noop,
onCloseTerminal: noop,
onWorkspaceSleep: noop,
onResumeSleepingAgents: noop,
onRevealEditorTabFromRuntime: (cb: (payload: RuntimeEditorTabReveal) => void) => {
reveal = cb
return () => {}
}
}
}
})
const store = createTestStore()
storeRef.current = store
seedStore(store, {
worktreesByRepo: {
repo1: [
makeWorktree({ id: WT, repoId: 'repo1', path: '/repo1/wt' }),
makeWorktree({ id: UNDRAWN, repoId: 'repo1', path: '/repo1/undrawn' })
]
}
})
store.getState().setActiveWorktree(WT)
store.setState({
openFiles: [
{
...FILE,
id: FILE.filePath,
worktreeId: WT,
language: 'markdown',
runtimeEnvironmentId: null,
isDirty: false,
mode: 'edit'
}
]
})
store.getState().createUnifiedTab(WT, 'editor', { entityId: FILE.filePath, label: 'notes.md' })
store.getState().createTab(WT)
const fileTab = store
.getState()
.unifiedTabsByWorktree[WT]!.find((tab) => tab.entityId === FILE.filePath)!
registerMobileAndTerminalCloseIpcBridge([], vi.fn())
if (!reveal) {
throw new Error('reveal listener was not registered')
}
return {
reveal,
tabId: fileTab.id,
activeWorktreeId: () => store.getState().activeWorktreeId,
store,
activeTabId: () => {
const state = store.getState()
const groupId = state.activeGroupIdByWorktree[WT]
return state.groupsByWorktree[WT]?.find((group) => group.id === groupId)?.activeTabId
}
}
}
afterEach(() => {
_resetLayoutFramePositionForTests()
vi.unstubAllGlobals()
})
describe('showing a tab main wrote for a file it opened', () => {
it('waits for the frame that draws the tab, then shows it', () => {
const h = setup()
beginLayoutFramePositions()
noteLayoutFramePosition(4)
h.reveal({ worktreeId: WT, ...FILE, tabId: h.tabId, frameSeq: 5 })
expect(h.activeTabId()).not.toBe(h.tabId)
noteLayoutFramePosition(5)
expect(h.activeTabId()).toBe(h.tabId)
})
it("visits a workspace the window has not drawn yet, then shows main's tab once it draws", async () => {
const h = setup()
beginLayoutFramePositions()
// Stands in for the frame sync: once the workspace draws, its flush brings main's tab in.
h.store.subscribe((state) => {
if (UNDRAWN in state.groupsByWorktree && !state.unifiedTabsByWorktree[UNDRAWN]?.length) {
queueMicrotask(() =>
h.store.getState().createUnifiedTab(UNDRAWN, 'editor', {
id: 'main-tab',
entityId: '/repo1/undrawn/notes.md'
})
)
}
})
h.reveal({ worktreeId: UNDRAWN, ...FILE, tabId: 'main-tab', navigation: 'host' })
expect(h.activeWorktreeId()).toBe(UNDRAWN)
// The window seeds the visited workspace's root group after render, a later task.
await Promise.resolve()
h.store.getState().ensureWorktreeRootGroup(UNDRAWN)
await vi.waitFor(() => {
const state = h.store.getState()
const group = state.groupsByWorktree[UNDRAWN]?.find(
(entry) => entry.id === state.activeGroupIdByWorktree[UNDRAWN]
)
expect(group?.activeTabId).toBe('main-tab')
expect(state.activeTabTypeByWorktree[UNDRAWN]).toBe('editor')
})
})
})
@@ -1,162 +0,0 @@
// @vitest-environment happy-dom
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { Toaster, toast } from 'sonner'
import { useAppStore } from '@/store/index'
import { getDefaultSettings } from '../../../../../../shared/constants'
import { makeFolderWorkspace } from '@/store/folder-workspaces/folder-workspace.test-fixture'
import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture'
import { launchAgentSessionContinuation } from './launch-agent-session-continuation'
import type { LaunchAgentInNewTabArgs } from '../new-tab/launch-agent-in-new-tab-args'
import type { LaunchAgentInNewTabResult } from '../new-tab/launch-agent-in-new-tab-host-agents'
const mocks = vi.hoisted(() => ({
launch: vi.fn<(args: LaunchAgentInNewTabArgs) => LaunchAgentInNewTabResult>()
}))
vi.mock('@/lib/agent-session/launch/new-tab/launch-agent-in-new-tab', () => ({
launchAgentInNewTabWithOutcome: mocks.launch
}))
vi.mock('@/runtime/native-chat/tab-retirement/structured-agent-session-tab-retirement', () => ({
beginStructuredAgentSessionTabClose: vi.fn()
}))
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) =>
(
await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture')
).runtimeRpcClientWithLayoutApply(await importOriginal())
)
vi.mock('../inventory/host-chat-program-acquisition', () => ({
acquireAgentLaunchChoices: async () => ({ detected: ['codex'], offered: ['codex'] })
}))
const initial = useAppStore.getState()
beforeEach(() => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
mocks.launch.mockReset()
mocks.launch.mockImplementation(({ worktreeId, agentSessionLaunchPlan }) => {
useAppStore.getState().createUnifiedTab(worktreeId, 'agent-session', {
id: 'agent-session:continuation',
entityId: 'continuation',
executionHostId: agentSessionLaunchPlan?.executionHostId,
agentSessionAgent: 'codex',
activate: false
})
return { surface: { kind: 'host-published' }, pasteDraftAfterLaunch: false }
})
useAppStore.setState({
settings: getDefaultSettings('/test'),
repos: [{ id: 'repo-1', path: '/repo', displayName: 'Repo', badgeColor: '', addedAt: 0 }],
worktreesByRepo: {
'repo-1': [
makeWorktree({ id: 'source', repoId: 'repo-1', path: '/repo/source', hostId: 'local' }),
makeWorktree({
id: 'target',
repoId: 'repo-1',
path: '/repo/target',
displayName: 'Destination worktree',
hostId: 'local'
})
]
},
folderWorkspaces: [
makeFolderWorkspace({
id: 'local-folder',
name: 'Local folder',
executionHostId: 'local'
}),
makeFolderWorkspace({
id: 'remote-folder',
name: 'Remote folder',
executionHostId: 'runtime:paired'
})
],
activeRepoId: 'repo-1',
activeWorktreeId: 'source',
activeWorkspaceExecutionHostId: 'local',
activeView: 'terminal',
refreshGitHubForWorktreeIfStale: vi.fn()
})
})
afterEach(() => {
cleanup()
toast.dismiss()
vi.clearAllTimers()
vi.useRealTimers()
useAppStore.setState(initial, true)
})
it.each([
{ worktreeId: 'target', executionHostId: 'local', name: 'Destination worktree' },
{ worktreeId: 'folder:local-folder', executionHostId: 'local', name: 'Local folder' },
{
worktreeId: 'folder:remote-folder',
executionHostId: 'runtime:paired',
name: 'Remote folder'
}
] as const)(
'names $name and opens its host only when the toast action is clicked',
async ({ worktreeId, executionHostId, name }) => {
render(<Toaster closeButton />)
await act(async () => {
await expect(
launchAgentSessionContinuation({
agent: 'codex',
prompt: 'Continue the saved task',
worktreeId,
launchSource: 'sidebar',
launchChoice: { agent: 'codex', route: 'structured-native-chat', executionHostId }
})
).resolves.toBe(true)
})
expect(screen.queryByText(name)).toBeNull()
expect(useAppStore.getState().activeWorktreeId).toBe('source')
await act(async () => {
mocks.launch.mock.calls[0]?.[0].onPromptDelivered?.()
await vi.advanceTimersByTimeAsync(0)
})
expect(screen.getByText(name)).toBeTruthy()
expect(useAppStore.getState().activeWorktreeId).toBe('source')
expect(useAppStore.getState().activeWorkspaceExecutionHostId).toBe('local')
fireEvent.click(screen.getByRole('button', { name: 'Go to workspace' }))
expect(useAppStore.getState().activeWorktreeId).toBe(worktreeId)
expect(useAppStore.getState().activeWorkspaceExecutionHostId).toBe(executionHostId)
expect(useAppStore.getState().unifiedTabsByWorktree[worktreeId]).toEqual([
expect.objectContaining({ id: 'agent-session:continuation', executionHostId })
])
expect(useAppStore.getState().tabsByWorktree[worktreeId] ?? []).toEqual([])
}
)
it.each(['target', 'folder:local-folder'])(
'recovers an empty %s when the continuation closes before clicking the toast',
async (worktreeId) => {
render(<Toaster closeButton />)
await act(async () => {
await launchAgentSessionContinuation({
agent: 'codex',
prompt: 'Continue the saved task',
worktreeId,
launchSource: 'sidebar',
launchChoice: {
agent: 'codex',
route: 'structured-native-chat',
executionHostId: 'local'
}
})
mocks.launch.mock.calls[0]?.[0].onPromptDelivered?.()
await vi.advanceTimersByTimeAsync(0)
})
useAppStore.getState().closeUnifiedTab('agent-session:continuation')
expect(useAppStore.getState().reconcileWorktreeTabModel(worktreeId).renderableTabCount).toBe(0)
expect(useAppStore.getState().activeWorktreeId).toBe('source')
fireEvent.click(screen.getByRole('button', { name: 'Go to workspace' }))
expect(useAppStore.getState().activeWorktreeId).toBe(worktreeId)
expect(useAppStore.getState().activeWorkspaceExecutionHostId).toBe('local')
expect(useAppStore.getState().tabsByWorktree[worktreeId]).toHaveLength(1)
}
)
@@ -1,216 +0,0 @@
import { describe, expect, it } from 'vitest'
import type {
BrowserPage,
BrowserWorkspace
} from '../../../../../shared/browser/workspaces/browser-workspace-types'
import type { Tab } from '../../../../../shared/tab-types'
import type { Worktree } from '../../../../../shared/worktree/types'
import { getWorktreeHostIdentity } from '../../../../../shared/worktree/host-qualified-identity'
import { buildSearchableBrowserPages } from './browser-palette-page-entries'
import { searchBrowserPages } from './browser-palette-search'
function makeWorktree(overrides: Partial<Worktree> = {}): Worktree {
return {
id: 'wt-1',
repoId: 'repo-1',
path: '/tmp/wt-1',
head: 'abc123',
branch: 'refs/heads/feature/browser-search',
isBare: false,
isMainWorktree: false,
displayName: 'Palette Worktree',
comment: '',
linkedIssue: null,
linkedPR: null,
linkedLinearIssue: null,
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 0,
...overrides
}
}
function makeWorkspace(overrides: Partial<BrowserWorkspace> = {}): BrowserWorkspace {
return {
id: 'ws-1',
worktreeId: 'wt-1',
activePageId: 'page-1',
pageIds: ['page-1'],
url: 'https://example.com',
title: 'Example',
loading: false,
faviconUrl: null,
canGoBack: false,
canGoForward: false,
loadError: null,
createdAt: 0,
...overrides
}
}
function makePage(overrides: Partial<BrowserPage> = {}): BrowserPage {
return {
id: 'page-1',
workspaceId: 'ws-1',
worktreeId: 'wt-1',
url: 'https://example.com/docs',
title: 'Project Docs',
loading: false,
faviconUrl: null,
canGoBack: false,
canGoForward: false,
loadError: null,
createdAt: 0,
...overrides
}
}
const repoMap = new Map([
['repo-1', { displayName: 'repo/one' }],
['repo-2', { displayName: 'repo/two' }]
])
const worktreeOrder = new Map([
['wt-1', 0],
['wt-2', 1]
])
describe('buildSearchableBrowserPages', () => {
it('keeps same-id browser tabs isolated by execution host', () => {
const sharedId = 'repo-shared::/workspace'
const local = makeWorktree({ id: sharedId, hostId: 'local', displayName: 'Local workspace' })
const remote = makeWorktree({
id: sharedId,
hostId: 'runtime:host-b',
displayName: 'Remote workspace'
})
const localWorkspace = makeWorkspace({
id: 'ws-local',
worktreeId: sharedId,
activePageId: 'page-local'
})
const remoteWorkspace = makeWorkspace({
id: 'ws-remote',
worktreeId: sharedId,
activePageId: 'page-remote'
})
const entries = buildSearchableBrowserPages({
worktrees: [local, remote],
repoMap,
worktreeOrder: new Map([
[getWorktreeHostIdentity(local), 0],
[getWorktreeHostIdentity(remote), 1]
]),
browserTabsByWorktree: {
[sharedId]: [localWorkspace, remoteWorkspace]
},
browserPagesByWorkspace: {
'ws-local': [
makePage({
id: 'page-local',
workspaceId: 'ws-local',
worktreeId: sharedId,
title: 'Local docs'
})
],
'ws-remote': [
makePage({
id: 'page-remote',
workspaceId: 'ws-remote',
worktreeId: sharedId,
title: 'Remote docs'
})
]
},
unifiedTabsByWorktree: {
[sharedId]: [
browserUnifiedTab('tab-local', 'ws-local', sharedId, 'local'),
browserUnifiedTab('tab-remote', 'ws-remote', sharedId, 'runtime:host-b')
]
},
activeBrowserTabId: null,
activeWorktreeId: null,
activeTabType: 'terminal'
})
expect(entries.map((entry) => [entry.page.id, entry.worktree.hostId])).toEqual([
['page-local', 'local'],
['page-remote', 'runtime:host-b']
])
expect(
searchBrowserPages(entries, 'docs').map((result) => [result.pageId, result.executionHostId])
).toEqual([
['page-local', 'local'],
['page-remote', 'runtime:host-b']
])
})
it('does not re-host a tab whose stamped owner is absent from the catalog', () => {
const sharedId = 'repo-shared::/workspace'
const remote = makeWorktree({ id: sharedId, hostId: 'runtime:host-b' })
const entries = buildSearchableBrowserPages({
worktrees: [remote],
repoMap,
worktreeOrder: new Map([[getWorktreeHostIdentity(remote), 0]]),
browserTabsByWorktree: {
[sharedId]: [
makeWorkspace({ id: 'ws-local', worktreeId: sharedId, activePageId: 'page-local' })
]
},
browserPagesByWorkspace: {
'ws-local': [makePage({ id: 'page-local', workspaceId: 'ws-local', worktreeId: sharedId })]
},
unifiedTabsByWorktree: {
[sharedId]: [browserUnifiedTab('tab-local', 'ws-local', sharedId, 'local')]
},
activeBrowserTabId: null,
activeWorktreeId: null,
activeTabType: 'terminal'
})
expect(entries).toEqual([])
})
it('does not route one ambiguous legacy browser bucket to both hosts', () => {
const sharedId = 'repo-shared::/workspace'
const workspace = makeWorkspace({ worktreeId: sharedId })
expect(
buildSearchableBrowserPages({
worktrees: [
makeWorktree({ id: sharedId, hostId: 'local' }),
makeWorktree({ id: sharedId, hostId: 'runtime:host-b' })
],
repoMap,
worktreeOrder,
browserTabsByWorktree: { [sharedId]: [workspace] },
browserPagesByWorkspace: { [workspace.id]: [makePage({ worktreeId: sharedId })] },
activeBrowserTabId: null,
activeWorktreeId: null,
activeTabType: 'terminal'
})
).toEqual([])
})
})
function browserUnifiedTab(
id: string,
entityId: string,
worktreeId: string,
executionHostId?: Tab['executionHostId']
): Tab {
return {
id,
entityId,
groupId: `group-${id}`,
worktreeId,
...(executionHostId ? { executionHostId } : {}),
contentType: 'browser',
label: entityId,
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 0
}
}
@@ -1,159 +0,0 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { WslMovePendingRendererRewrite } from '../../../../../shared/wsl-move/wsl-move-renderer-rewrite-types'
import { WSL_MOVE_RENDERER_REWRITE_STORE_IDS } from '../../../../../shared/wsl-move/wsl-move-renderer-rewrite-types'
import type * as RunnerModule from './wsl-move-renderer-store-rewrites'
const client = vi.hoisted(() => ({
list: vi.fn<() => Promise<WslMovePendingRendererRewrite[]>>(),
record: vi.fn()
}))
vi.mock('./wsl-move-renderer-rewrite-client', () => ({
listPendingWslMoveRendererRewrites: client.list,
recordWslMoveRendererStoreRewritten: client.record
}))
vi.mock('@/store/index', () => ({ useAppStore: { getState: () => ({}) } }))
const UNC_ROOT = '\\\\wsl.localhost\\Ubuntu\\home\\u\\proj'
const LOCAL_ID = `repo-1::${UNC_ROOT}`
const HOST_ID = 'repo-1::/home/u/proj'
const QUICK_OPEN = 'orca.quick-open-history.v1'
const PDF = 'orca.pdf.scale-preferences.v1'
const CSV = 'orca.csv.column-widths.v1'
const NOTEBOOKS = 'orca.notebookPythonEnvironments'
const APPLIED = 'orca.wsl-move.renderer-rewrites.v1'
const localRoute = { executionHostId: 'local', runtimeEnvironmentId: null }
const hostRoute = { executionHostId: 'runtime:wsl-env', runtimeEnvironmentId: 'wsl-env' }
const localQuickOpen = JSON.stringify([localRoute, LOCAL_ID, '//wsl/ubuntu/home/u/proj'])
const hostQuickOpen = JSON.stringify([hostRoute, HOST_ID, '/home/u/proj'])
const sshQuickOpen = JSON.stringify([
{ executionHostId: 'ssh:box', runtimeEnvironmentId: null },
'repo-9::/srv/x',
'/srv/x'
])
const localPdf = JSON.stringify([LOCAL_ID, 'local', null, `${UNC_ROOT}\\a.pdf`])
const hostPdf = JSON.stringify([HOST_ID, 'wsl-env', null, '/home/u/proj/a.pdf'])
const localCsv = JSON.stringify([
JSON.stringify([LOCAL_ID, 'local', null, `${UNC_ROOT}\\a.csv`]),
','
])
const hostCsv = JSON.stringify([
JSON.stringify([HOST_ID, 'wsl-env', null, '/home/u/proj/a.csv']),
','
])
function move(
overrides: Partial<WslMovePendingRendererRewrite> = {}
): WslMovePendingRendererRewrite {
return {
migrationId: 'move-1',
storeIds: [...WSL_MOVE_RENDERER_REWRITE_STORE_IDS],
destinationEnvironmentId: 'wsl-env',
destinationHostId: 'runtime:wsl-env',
distro: 'Ubuntu',
scopeRepoIds: ['repo-1'],
scopeFolderWorkspaceIds: [],
scopeRootPaths: ['/home/u/proj'],
...overrides
}
}
function seedStorage(): void {
localStorage.setItem(
QUICK_OPEN,
JSON.stringify([
[sshQuickOpen, ['x.ts']],
[localQuickOpen, ['src/a.ts']]
])
)
localStorage.setItem(PDF, JSON.stringify({ [localPdf]: { scale: 1.5 } }))
localStorage.setItem(CSV, JSON.stringify({ [localCsv]: { 0: 120 } }))
localStorage.setItem(
NOTEBOOKS,
JSON.stringify({
[`${UNC_ROOT}\\nb.ipynb`]: { path: `${UNC_ROOT}\\.venv\\bin\\python`, name: '.venv' }
})
)
}
const read = (key: string): unknown => JSON.parse(localStorage.getItem(key) ?? 'null')
// A fresh module graph is a renderer reload: in-memory caches start over from storage.
async function loadRunner(): Promise<typeof RunnerModule> {
vi.resetModules()
return import('./wsl-move-renderer-store-rewrites')
}
beforeEach(() => {
localStorage.clear()
client.list.mockReset()
client.record.mockReset()
client.record.mockResolvedValue({ recorded: true })
})
afterEach(() => {
vi.doUnmock('../../../components/editor/notebook/kernel/ipynb-kernel-store')
})
describe('WSL move renderer store rewrites', () => {
it('adds a host copy beside each moved entry, then records every store', async () => {
seedStorage()
client.list.mockResolvedValue([move()])
await (await loadRunner()).runWslMoveRendererStoreRewrites()
expect(read(QUICK_OPEN)).toEqual([
[sshQuickOpen, ['x.ts']],
[localQuickOpen, ['src/a.ts']],
[hostQuickOpen, ['src/a.ts']]
])
expect(read(PDF)).toEqual({ [localPdf]: { scale: 1.5 }, [hostPdf]: { scale: 1.5 } })
expect(read(CSV)).toEqual({ [localCsv]: { 0: 120 }, [hostCsv]: { 0: 120 } })
expect(read(NOTEBOOKS)).toMatchObject({
'/home/u/proj/nb.ipynb': { path: '/home/u/proj/.venv/bin/python', name: '.venv' }
})
expect(client.record.mock.calls).toEqual(
WSL_MOVE_RENDERER_REWRITE_STORE_IDS.map((id) => ['move-1', id])
)
})
it('does not re-apply a landed store after a reload, but still records it if pending', async () => {
seedStorage()
client.list.mockResolvedValue([move()])
await (await loadRunner()).runWslMoveRendererStoreRewrites()
// The user drops the host copy afterwards; a reload must not bring it back.
const pdf = { [localPdf]: { scale: 1.5 } }
localStorage.setItem(PDF, JSON.stringify(pdf))
client.record.mockClear()
await (await loadRunner()).runWslMoveRendererStoreRewrites()
expect(read(PDF)).toEqual(pdf)
expect(client.record).toHaveBeenCalledTimes(WSL_MOVE_RENDERER_REWRITE_STORE_IDS.length)
})
it('makes room in a full store by dropping the moved source, never another project', async () => {
const others = Array.from({ length: 63 }, (_, index) => [`other-${index}`, ['x.ts']])
localStorage.setItem(QUICK_OPEN, JSON.stringify([[localQuickOpen, ['src/a.ts']], ...others]))
client.list.mockResolvedValue([move()])
await (await loadRunner()).runWslMoveRendererStoreRewrites()
expect(read(QUICK_OPEN)).toEqual([[hostQuickOpen, ['src/a.ts']], ...others])
})
it('neither marks nor records a store whose write storage refused', async () => {
seedStorage()
client.list.mockResolvedValue([move()])
const setItem = localStorage.setItem.bind(localStorage)
const refuse = vi.spyOn(localStorage, 'setItem').mockImplementation((key, value) => {
if (key === QUICK_OPEN) {
throw new Error('quota')
}
setItem(key, value)
})
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
await (await loadRunner()).runWslMoveRendererStoreRewrites()
refuse.mockRestore()
warn.mockRestore()
expect(client.record).not.toHaveBeenCalledWith('move-1', 'quick-open-history')
expect(read(APPLIED)).not.toContain('move-1:quick-open-history')
})
})
@@ -1,171 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { RuntimeMobileSessionTabsResult } from '../../../../../shared/remote-runtime/session-graph/runtime-session-contracts'
import { toWebTerminalSurfaceTabId } from '../../../../../shared/workspace-layout/terminal-surface-id'
import '../../../../../shared/agent-session/view/structured-agent-session-projection'
import '../../../../../shared/constants'
import {
clearWebSessionCloseIntent,
recordWebSessionCloseIntent
} from '../closing/web-session-close-intent'
import { recordWebSessionReorderIntent } from './web-session-reorder-intent'
import { acceptReplayedWebSessionTabsSnapshot, type WebSessionTabsSyncState } from '../state'
import { applyFreshWebSessionTabsSnapshot, applyWebSessionTabsSnapshot } from '../snapshot-api'
import '../tracking-mappings'
import '../tracking-decisions'
import '../tracking'
import {
ENV,
HOST_SURFACE_ID,
LEAF_ID,
NOW,
SECOND_LEAF_ID,
WT,
makeSnapshot,
makeState,
resetWebSessionTabsSyncTestState
} from '../testing/web-session-tabs-sync.test-fixture'
vi.mock('../../../store/index', () => ({
useAppStore: {
setState: vi.fn(),
// Snapshot receipt reads the held paired-tab closes; none here.
getState: () => ({})
}
}))
vi.mock('@/hooks/agent-hook-completion-notifications', () => ({
observeAgentHookCompletionForNotification: vi.fn()
}))
describe('applyWebSessionTabsSnapshot', () => {
beforeEach(resetWebSessionTabsSyncTestState)
it('suppresses a tab the client is closing until the host confirms removal (no close flash)', () => {
const surface = {
type: 'terminal' as const,
id: HOST_SURFACE_ID,
parentTabId: 'host-tab-1',
leafId: LEAF_ID,
title: 'Terminal',
status: 'ready' as const,
terminal: 'term_host',
isActive: true
}
// Client closed host-tab-1; an in-flight pre-close snapshot still lists it.
recordWebSessionCloseIntent({ environmentId: ENV }, WT, 'host-tab-1', NOW)
const stalePreClose = applyWebSessionTabsSnapshot(
makeState(),
makeSnapshot([surface]),
ENV,
NOW
)
expect((stalePreClose.tabsByWorktree?.[WT] ?? []).map((tab) => tab.id)).not.toContain(
toWebTerminalSurfaceTabId('host-tab-1')
)
// Host omission clears close intent; a genuinely new tab reusing that ID must show.
applyWebSessionTabsSnapshot(makeState(), makeSnapshot([]), ENV, NOW + 1)
const reopened = applyWebSessionTabsSnapshot(
makeState(),
makeSnapshot([surface], { snapshotVersion: 5 }),
ENV,
NOW + 2
)
expect((reopened.tabsByWorktree?.[WT] ?? []).map((tab) => tab.id)).toContain(
toWebTerminalSurfaceTabId('host-tab-1')
)
})
it('reapplies an unchanged host snapshot after a lifecycle close is refused', () => {
const surface = {
type: 'terminal' as const,
id: HOST_SURFACE_ID,
parentTabId: 'host-tab-1',
leafId: LEAF_ID,
title: 'Terminal',
status: 'ready' as const,
terminal: 'term_host',
isActive: true
}
const authoritative = makeSnapshot([surface], { snapshotVersion: 6 })
const initial = makeState()
recordWebSessionCloseIntent({ environmentId: ENV }, WT, 'host-tab-1', NOW)
const hiddenPatch = applyFreshWebSessionTabsSnapshot(initial, authoritative, ENV, NOW)
const hidden = { ...initial, ...(hiddenPatch as Partial<WebSessionTabsSyncState>) }
expect((hidden.tabsByWorktree[WT] ?? []).map((tab) => tab.id)).not.toContain(
toWebTerminalSurfaceTabId('host-tab-1')
)
// Live-PTY refusal needs unchanged snapshot replay immediately, without waiting for a publish.
clearWebSessionCloseIntent({ environmentId: ENV }, WT, 'host-tab-1')
acceptReplayedWebSessionTabsSnapshot(ENV, WT)
const restoredPatch = applyFreshWebSessionTabsSnapshot(hidden, authoritative, ENV, NOW + 1)
const restored = { ...hidden, ...(restoredPatch as Partial<WebSessionTabsSyncState>) }
expect((restored.tabsByWorktree[WT] ?? []).map((tab) => tab.id)).toContain(
toWebTerminalSurfaceTabId('host-tab-1')
)
})
it('keeps a client reorder until the host echoes it (no order snap-back)', () => {
const local1 = toWebTerminalSurfaceTabId('host-tab-1')
const local2 = toWebTerminalSurfaceTabId('host-tab-2')
const surfaces: RuntimeMobileSessionTabsResult['tabs'] = [
{
type: 'terminal',
id: `host-tab-1::${LEAF_ID}`,
parentTabId: 'host-tab-1',
leafId: LEAF_ID,
title: 'Terminal 1',
status: 'ready',
terminal: 'term_host_1',
isActive: true
},
{
type: 'terminal',
id: `host-tab-2::${SECOND_LEAF_ID}`,
parentTabId: 'host-tab-2',
leafId: SECOND_LEAF_ID,
title: 'Terminal 2',
status: 'ready',
terminal: 'term_host_2',
isActive: false
}
]
const groupWithOrder = (tabOrder: string[]): RuntimeMobileSessionTabsResult['tabGroups'] => [
{ id: 'host-group-1', activeTabId: 'host-tab-1', tabOrder }
]
// Optimistic reorder must survive in-flight pre-move host order.
recordWebSessionReorderIntent({ environmentId: ENV }, WT, 'host-group-1', [local2, local1], NOW)
const stalePreMove = applyWebSessionTabsSnapshot(
makeState(),
makeSnapshot(surfaces, { tabGroups: groupWithOrder(['host-tab-1', 'host-tab-2']) }),
ENV,
NOW
) as Partial<WebSessionTabsSyncState>
expect(stalePreMove.groupsByWorktree?.[WT]?.[0]?.tabOrder).toEqual([local2, local1])
// Host confirmation clears reorder intent; later host order changes must apply.
applyWebSessionTabsSnapshot(
makeState(),
makeSnapshot(surfaces, {
snapshotVersion: 5,
tabGroups: groupWithOrder(['host-tab-2', 'host-tab-1'])
}),
ENV,
NOW + 1
)
const reverted = applyWebSessionTabsSnapshot(
makeState(),
makeSnapshot(surfaces, {
snapshotVersion: 6,
tabGroups: groupWithOrder(['host-tab-1', 'host-tab-2'])
}),
ENV,
NOW + 2
) as Partial<WebSessionTabsSyncState>
expect(reverted.groupsByWorktree?.[WT]?.[0]?.tabOrder).toEqual([local1, local2])
})
})
@@ -1,179 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createTestStore } from '../testing/app-store-test-fixture'
import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types'
import type { ProjectGroup } from '../../../../shared/project/groups/project-group-types'
import type { Repo } from '../../../../shared/repository/repo-types'
import {
createCompatibleRuntimeStatusResponseIfNeeded,
type RuntimeEnvironmentCallRequest
} from '../../runtime/rpc/testing/runtime-compatibility-test-fixture'
import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '../../runtime/rpc/compatibility/runtime-compatibility-cache'
import { folderWorkspaceKey } from '../../../../shared/workspace/identity/workspace-scope'
const localRepo: Repo = {
id: 'local-repo',
path: '/l',
displayName: 'L',
badgeColor: '#000',
addedAt: 1
}
const remoteRepo: Repo = {
id: 'remote-repo',
path: '/r',
displayName: 'R',
badgeColor: '#000',
addedAt: 1
}
const group = (id: string, parentPath: string): ProjectGroup => ({
id,
name: id,
parentPath,
parentGroupId: null,
createdFrom: 'manual',
tabOrder: 0,
isCollapsed: false,
color: null,
createdAt: 1,
updatedAt: 1
})
const folder = (id: string, projectGroupId: string, folderPath: string): FolderWorkspace => ({
id,
projectGroupId,
name: id,
folderPath,
linkedTask: null,
comment: '',
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 1,
createdAt: 1,
updatedAt: 1
})
const localGroup = group('local-group', '/l')
const remoteGroup = group('remote-group', '/r')
const localFolder = folder('local-folder', 'local-group', '/l')
const remoteFolder = folder('remote-folder', 'remote-group', '/r')
const restoredFolderKey = folderWorkspaceKey('remote-folder')
const reposList = vi.fn()
const projectGroupsList = vi.fn()
const folderWorkspacesList = vi.fn()
const runtimeEnvironmentsList = vi.fn()
const runtimeEnvironmentCall = vi.fn()
function rpc(result: unknown): unknown {
return { id: 'rpc', ok: true, result, _meta: { runtimeId: 'runtime-remote' } }
}
function remoteResult(method: string): unknown {
switch (method) {
case 'repo.list':
return rpc({ repos: [remoteRepo] })
case 'projectGroup.list':
return rpc({ groups: [remoteGroup] })
case 'folderWorkspace.list':
return rpc({ folderWorkspaces: [remoteFolder] })
case 'settings.get':
return rpc({ settings: { worktreeVisibilityDefaults: { external: 'show' } } })
default:
return rpc({ projects: [], setups: [] })
}
}
beforeEach(() => {
clearRuntimeCompatibilityCacheForTests()
for (const mock of [
reposList,
projectGroupsList,
folderWorkspacesList,
runtimeEnvironmentsList,
runtimeEnvironmentCall
]) {
mock.mockReset()
}
reposList.mockResolvedValue([localRepo])
projectGroupsList.mockResolvedValue([localGroup])
folderWorkspacesList.mockResolvedValue([localFolder])
runtimeEnvironmentsList.mockResolvedValue([{ id: 'env-1', name: 'remote' }])
runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) =>
remoteResult(args.method)
)
vi.stubGlobal('window', {
api: {
repos: { list: reposList },
projects: {
list: vi.fn().mockResolvedValue([]),
listHostSetups: vi.fn().mockResolvedValue([])
},
projectGroups: { list: projectGroupsList },
folderWorkspaces: { list: folderWorkspacesList },
runtimeEnvironments: {
list: runtimeEnvironmentsList,
call: (args: RuntimeEnvironmentCallRequest) =>
createCompatibleRuntimeStatusResponseIfNeeded(args) ?? runtimeEnvironmentCall(args)
}
},
dispatchEvent: vi.fn()
})
vi.spyOn(console, 'error').mockImplementation(() => {})
vi.spyOn(console, 'warn').mockImplementation(() => {})
})
function storeWithRestoredFolderOwner(): ReturnType<typeof createTestStore> {
const store = createTestStore()
store.setState({
projectGroups: [
{ ...localGroup, executionHostId: 'local' },
{ ...remoteGroup, executionHostId: 'runtime:env-1' }
],
restoredRuntimeHostIdByWorkspaceSessionKey: { [restoredFolderKey]: 'runtime:env-1' }
})
return store
}
describe('all-host folder workspace settlement', () => {
it('drops a restored owner its own host settled even when the local catalog fails', async () => {
folderWorkspacesList.mockRejectedValue(new Error('local down'))
const store = storeWithRestoredFolderOwner()
await store.getState().fetchFolderWorkspacesForAllHosts()
expect(store.getState().folderWorkspaces.map((w) => w.id)).toEqual(['remote-folder'])
expect(store.getState().restoredRuntimeHostIdByWorkspaceSessionKey).toEqual({})
})
})
describe('all-host repo settlement', () => {
it('settles the local waiter with the error and still loads remote repos when local fails', async () => {
const localError = new Error('local down')
reposList.mockRejectedValue(localError)
const store = createTestStore()
await store.getState().fetchReposForAllHosts()
await expect(store.getState().awaitLocalRepoCatalogSettlement()).rejects.toBe(localError)
expect(store.getState().repos.map((r) => r.id)).toEqual(['remote-repo'])
})
it('applies visibility defaults but keeps saved filters when one remote repo catalog fails', async () => {
runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => {
if (args.method === 'repo.list') {
throw new Error('runtime_unreachable')
}
return remoteResult(args.method)
})
const store = createTestStore()
store.setState({ activeRepoId: 'remote-repo', filterRepoIds: ['remote-repo'] })
await store.getState().fetchReposForAllHosts()
expect(store.getState().repos.map((r) => r.id)).toEqual(['local-repo'])
expect(store.getState().worktreeVisibilityDefaultsByHost['runtime:env-1']).toEqual({
external: 'show'
})
expect(store.getState().activeRepoId).toBe('remote-repo')
expect(store.getState().filterRepoIds).toEqual(['remote-repo'])
})
})
@@ -1,158 +0,0 @@
// With main layout ownership, each split and tab must reach main together; drawn frames must preserve group parity.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as AgentStatusModule from '@/lib/agent-status/aggregation/worktree-agent-status'
import { createTestStore, seedStore } from '../../testing/app-store-test-fixture'
import { makeWorktree } from '../worktrees/worktree.test-fixture'
import { createStoreCascadesMockApi } from '../../testing/app-store-cascade-api.test-fixture'
import '@/runtime/workspace-layout/commands/layout-owner-new-group-split'
import '@/runtime/workspace-layout/intents/layout-owner-content-tab-open'
import './content-tab-open-placement'
import { layoutApplyTestTransport } from '@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture'
import type { TabGroupLayoutNode } from '../../../../../shared/tab-types'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-switch'
import type { LayoutCommand } from '../../../../../shared/workspace-layout/workspace-layout-command-types'
import { drawTabsFromMain, type TabsDrawnFromMain } from './tabs-drawn-from-main.test-fixture'
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) =>
(
await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture')
).runtimeRpcClientWithLayoutApply(await importOriginal())
)
vi.mock('@/runtime/workspace-layout/frames/runtime-layout-client', async (importOriginal) =>
(
await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture')
).runtimeLayoutClientWithTestFrames(await importOriginal())
)
vi.mock('sonner', () => ({
toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() }
}))
vi.mock('@/lib/agent-status/aggregation/worktree-agent-status', async (importOriginal) => {
const actual = await importOriginal<typeof AgentStatusModule>()
return { ...actual, detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) }
})
createStoreCascadesMockApi()
const WT = 'repo1::/path/wt1'
const ROOT = 'group-root'
let store: ReturnType<typeof createTestStore>
let main: TabsDrawnFromMain
let sentSoFar = 0
beforeEach(async () => {
store = createTestStore()
seedStore(store, {
worktreesByRepo: { repo1: [makeWorktree({ id: WT, repoId: 'repo1', path: '/path/wt1' })] },
activeWorktreeId: WT,
groupsByWorktree: { [WT]: [{ id: ROOT, worktreeId: WT, activeTabId: null, tabOrder: [] }] },
activeGroupIdByWorktree: { [WT]: ROOT },
unifiedTabsByWorktree: { [WT]: [] }
})
main = await drawTabsFromMain(store)
sentSoFar = 0
})
afterEach(() => {
main.close()
})
/** What the window sent since the last call, once main answered it and its frames are drawn. */
async function settledSent(): Promise<LayoutCommand[]> {
await main.settle()
const sent = layoutApplyTestTransport.sent.slice(sentSoFar)
sentSoFar = layoutApplyTestTransport.sent.length
return [...sent]
}
/** Groups by id: the detector matches them by id, and main appends a group the window kept. */
function byId(groups: readonly { id: string; tabOrder: string[] }[]) {
return groups
.map(({ id, tabOrder }) => ({ id, tabOrder }))
.sort((left, right) => left.id.localeCompare(right.id))
}
/** The window's groups that hold tabs: main stores no empty group. */
function windowView() {
const state = store.getState()
return {
groups: byId((state.groupsByWorktree[WT] ?? []).filter((group) => group.tabOrder.length > 0)),
tree: splitTree(state.layoutByWorktree[WT])
}
}
function mainView() {
const workspace = layoutApplyTestTransport.mainModel!.workspaces[WT]!
return {
groups: byId(workspace.groups),
tree: splitTree(workspace.groupLayout)
}
}
/** A lone group's tree is implied: the window stores its leaf, main none. */
function splitTree(tree: TabGroupLayoutNode | undefined): TabGroupLayoutNode | null {
return tree?.type === 'split' ? tree : null
}
function openFile(path: string, options?: { preview?: boolean; targetGroupId?: string }) {
store
.getState()
.openFile(
{ filePath: path, relativePath: path.slice(1), worktreeId: WT, language: 'ts', mode: 'edit' },
options
)
}
function onlyTabOf(groupId: string): string {
const group = store.getState().groupsByWorktree[WT]!.find((entry) => entry.id === groupId)!
expect(group.tabOrder).toHaveLength(1)
return group.tabOrder[0]!
}
describe.runIf(ORCA_LAYOUT_OWNER_IS_MAIN)('open to the side in a layout-owner build', () => {
it('makes each new split in main with its tab, so main and the window agree after every step', async () => {
openFile('/a.ts')
await settledSent()
expect(mainView()).toEqual(windowView())
const editorGroup = store.getState().createEmptySplitGroup(WT, ROOT, 'right')!
openFile('/a.ts', { targetGroupId: editorGroup })
expect(await settledSent()).toEqual([
expect.objectContaining({
type: 'openEditorTab',
tabId: onlyTabOf(editorGroup),
groupId: editorGroup,
split: { besideGroupId: ROOT, direction: 'right' }
})
])
expect(mainView()).toEqual(windowView())
store.getState().createTab(WT, undefined, undefined, {
split: { sourceGroupId: editorGroup, splitDirection: 'down' }
})
const terminalGroup = store.getState().groupsByWorktree[WT]!.at(-1)!.id
const browser = store.getState().createBrowserTab(WT, 'about:blank', {
split: { sourceGroupId: ROOT, splitDirection: 'left' }
})
const sentNow = await settledSent()
const browserGroup = store
.getState()
.unifiedTabsByWorktree[WT]!.find((tab) => tab.entityId === browser.id)!.groupId
expect(sentNow).toEqual([
expect.objectContaining({
type: 'createTerminalTab',
tabId: onlyTabOf(terminalGroup),
groupId: terminalGroup,
split: { besideGroupId: editorGroup, direction: 'down' }
}),
expect.objectContaining({
type: 'openBrowserTab',
tabId: onlyTabOf(browserGroup),
groupId: browserGroup,
split: { besideGroupId: ROOT, direction: 'left' }
})
])
expect(mainView()).toEqual(windowView())
expect(mainView().groups).toHaveLength(4)
})
})
@@ -1,176 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { AppState } from '../../../types'
import type { RuntimeEnvironmentCallRequest } from '../../../../runtime/rpc/testing/runtime-compatibility-test-fixture'
import { clearHugeRepoWarningDismissalsForTests } from '@/lib/source-control/warnings/source-control-huge-repo-warning-dismissals'
import { worktreeWorkspaceKey } from '../../../../../../shared/workspace/identity/workspace-scope'
import { makeDetectedResult } from '../listing/worktrees-detected-listing-fixtures'
import { makeLineage, makeWorkspaceLineage } from './workspace-lineage.test-fixture'
import { makeWorktree } from '../worktree.test-fixture'
import { TEST_REPO } from '../../../repos/repo.test-fixture'
// The client stamps a server's repo row on arrival; focus alone never names the owner.
function createRemoteRepoStore() {
const store = createTestStore()
store.setState({ repos: [{ ...TEST_REPO, executionHostId: 'runtime:env-1' }] })
return store
}
import {
createTestStore,
resetRemoteRuntimeMocks,
resetWorktreeSliceModuleMemory,
runtimeEnvironmentCall
} from '../worktrees-slice-test-harness'
const requestWorktreeBaseFallbackNotice = vi.hoisted(() => vi.fn())
vi.mock('sonner', () => ({
toast: {
warning: vi.fn(),
info: vi.fn(),
success: vi.fn(),
error: vi.fn(),
dismiss: vi.fn()
}
}))
vi.mock('@/components/worktree-base-fallback-notice', () => ({
requestWorktreeBaseFallbackNotice
}))
beforeEach(resetWorktreeSliceModuleMemory)
describe('fetchWorktrees', () => {
beforeEach(() => {
vi.clearAllMocks()
resetRemoteRuntimeMocks()
clearHugeRepoWarningDismissalsForTests()
})
it('keeps a parent reassignment written while the host lineage request was in flight', async () => {
const store = createRemoteRepoStore()
const worktree = makeWorktree({
id: 'repo1::/remote/wt1',
repoId: 'repo1',
path: '/remote/wt1',
branch: 'refs/heads/remote',
hostId: 'runtime:env-1'
})
const childKey = worktreeWorkspaceKey(worktree.id)
const before = makeLineage({
worktreeId: worktree.id,
parentWorktreeId: 'repo1::/remote/old-parent'
})
const beforeWorkspace = makeWorkspaceLineage({
childWorkspaceKey: childKey,
parentWorkspaceKey: worktreeWorkspaceKey('repo1::/remote/old-parent')
})
store.setState({
settings: { activeRuntimeEnvironmentId: 'env-1' } as never,
worktreesByRepo: { repo1: [worktree] },
worktreeLineageById: { [before.worktreeId]: before },
workspaceLineageByChildKey: { [childKey]: beforeWorkspace }
} as Partial<AppState>)
let releaseLineage: (() => void) | undefined
const lineageReplied = new Promise<void>((resolve) => {
releaseLineage = resolve
})
runtimeEnvironmentCall.mockImplementation(async ({ method }: RuntimeEnvironmentCallRequest) => {
if (method === 'worktree.lineageList') {
await lineageReplied
return {
id: 'rpc-1',
ok: true,
result: {
lineage: { [before.worktreeId]: before },
workspaceLineage: { [childKey]: beforeWorkspace }
},
_meta: { runtimeId: 'runtime-remote' }
}
}
return {
id: 'rpc-2',
ok: true,
result: makeDetectedResult('repo1', [worktree]),
_meta: { runtimeId: 'runtime-remote' }
}
})
const pending = store.getState().fetchWorktreeLineage({ executionHostId: 'runtime:env-1' })
const reassigned = makeLineage({
worktreeId: worktree.id,
parentWorktreeId: 'repo1::/remote/new-parent'
})
const reassignedWorkspace = makeWorkspaceLineage({
childWorkspaceKey: childKey,
parentWorkspaceKey: worktreeWorkspaceKey('repo1::/remote/new-parent')
})
store.setState({
worktreeLineageById: { [reassigned.worktreeId]: reassigned },
workspaceLineageByChildKey: { [childKey]: reassignedWorkspace }
} as Partial<AppState>)
releaseLineage?.()
await pending
expect(store.getState().worktreeLineageById).toEqual({ [reassigned.worktreeId]: reassigned })
expect(store.getState().workspaceLineageByChildKey).toEqual({ [childKey]: reassignedWorkspace })
})
it('keeps a lineage row deleted while the host lineage request was in flight', async () => {
const store = createRemoteRepoStore()
const worktree = makeWorktree({
id: 'repo1::/remote/wt1',
repoId: 'repo1',
path: '/remote/wt1',
branch: 'refs/heads/remote',
hostId: 'runtime:env-1'
})
const childKey = worktreeWorkspaceKey(worktree.id)
const before = makeLineage({ worktreeId: worktree.id })
const beforeWorkspace = makeWorkspaceLineage({ childWorkspaceKey: childKey })
store.setState({
settings: { activeRuntimeEnvironmentId: 'env-1' } as never,
worktreesByRepo: { repo1: [worktree] },
worktreeLineageById: { [before.worktreeId]: before },
workspaceLineageByChildKey: { [childKey]: beforeWorkspace }
} as Partial<AppState>)
let releaseLineage: (() => void) | undefined
const lineageReplied = new Promise<void>((resolve) => {
releaseLineage = resolve
})
runtimeEnvironmentCall.mockImplementation(async ({ method }: RuntimeEnvironmentCallRequest) => {
if (method === 'worktree.lineageList') {
await lineageReplied
return {
id: 'rpc-1',
ok: true,
result: {
lineage: { [before.worktreeId]: before },
workspaceLineage: { [childKey]: beforeWorkspace }
},
_meta: { runtimeId: 'runtime-remote' }
}
}
return {
id: 'rpc-2',
ok: true,
result: makeDetectedResult('repo1', [worktree]),
_meta: { runtimeId: 'runtime-remote' }
}
})
const pending = store.getState().fetchWorktreeLineage({ executionHostId: 'runtime:env-1' })
store.setState({
worktreeLineageById: {},
workspaceLineageByChildKey: {}
} as Partial<AppState>)
releaseLineage?.()
await pending
expect(store.getState().worktreeLineageById).toEqual({})
expect(store.getState().workspaceLineageByChildKey).toEqual({})
})
})
@@ -1,86 +0,0 @@
import { describe, expect, it } from 'vitest'
import { findSecureDaclViolation } from './windows-secure-dacl'
import { daclFromSddl } from './windows-security-addon.test-fixture'
const USER = 'S-1-5-21-432636774-4279371817-3971399515-1001'
const fileViolation = (sddl: string) => findSecureDaclViolation(daclFromSddl(sddl), USER, false)
const directoryViolation = (sddl: string) => findSecureDaclViolation(daclFromSddl(sddl), USER, true)
describe('findSecureDaclViolation', () => {
// No migration: these are byte-for-byte what the icacls hardening left on this machine.
it('accepts what the icacls-era hardening left on disk', () => {
expect(fileViolation(`D:PAI(A;;FA;;;BA)(A;;FA;;;SY)(A;;FA;;;${USER})`)).toBeNull()
expect(
directoryViolation(`D:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;${USER})`)
).toBeNull()
})
it('accepts a protected DACL granting the user alone, and ignores deny rules', () => {
expect(fileViolation(`D:P(A;;FA;;;${USER})`)).toBeNull()
expect(fileViolation(`D:P(D;;FA;;;WD)(A;;FA;;;${USER})`)).toBeNull()
expect(fileViolation(`D:P(A;;0x1f01ff;;;${USER})`)).toBeNull()
expect(fileViolation(`D:P(A;;GA;;;${USER})`)).toBeNull()
})
it.each([
['explicit Everyone', `D:P(A;;FA;;;${USER})(A;;FR;;;WD)`, 'S-1-1-0'],
[
'inherited Authenticated Users (a relocated root)',
`D:AI(A;ID;FA;;;${USER})(A;ID;0x1301bf;;;AU)`,
'S-1-5-11'
],
[
'inherit-only Users on a directory',
`D:P(A;OICI;FA;;;${USER})(A;OICIIO;FR;;;BU)`,
'S-1-5-32-545'
]
])('rejects %s', (_label, sddl, sid) => {
expect(directoryViolation(sddl)).toBe(`unexpected rule for ${sid}`)
})
// Object, callback and conditional ACEs can grant by rules this check cannot evaluate.
it.each([
['last', `D:P(A;;FA;;;SY)(A;;FA;;;${USER})(XA;;FA;;;WD;(@User.Department == "Finance"))`],
['first', `D:P(XA;;FA;;;WD;(@User.Department == "Finance"))(A;;FA;;;SY)(A;;FA;;;${USER})`],
['an object ACE', `D:P(A;;FA;;;${USER})(OA;;FR;;;WD)`]
])('fails closed on an ACE it cannot evaluate: %s', (_label, sddl) => {
expect(fileViolation(sddl)).toMatch(/unsupported ACE type/)
})
// Loosening the parent reaches anything that still inherits, however tidy it looks today.
it('requires protection, even when every inherited rule names an allowed principal', () => {
expect(directoryViolation(`D:AI(A;OICIID;FA;;;SY)(A;OICIID;FA;;;${USER})`)).toMatch(
/not protected/
)
expect(fileViolation(`D:AI(A;ID;FA;;;SY)(A;ID;FA;;;BA)(A;ID;FA;;;${USER})`)).toMatch(
/not protected/
)
})
// An inherit-only rule grants the directory itself nothing, so Orca could not write into it.
it('rejects a path the user cannot actually use', () => {
const missing = `missing full control for ${USER}`
expect(directoryViolation(`D:P(A;OICIIO;FA;;;${USER})(A;OICI;FA;;;SY)`)).toBe(missing)
expect(directoryViolation(`D:P(A;;FA;;;${USER})`)).toBe(missing)
expect(fileViolation(`D:P(A;;FR;;;${USER})`)).toBe(missing)
})
it('fails closed on a NULL DACL, which grants everyone everything', () => {
expect(findSecureDaclViolation(null, USER, false)).toMatch(/NULL DACL/)
})
// The addon hands back raw SIDs, so the built-in Administrator (the CI runner) needs no alias.
it('checks a RID-500 user by its raw SID', () => {
const builtinAdmin = 'S-1-5-21-432636774-4279371817-3971399515-500'
expect(
findSecureDaclViolation(
daclFromSddl(`D:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;${builtinAdmin})`),
builtinAdmin,
true
)
).toBeNull()
expect(fileViolation(`D:P(A;;FA;;;${builtinAdmin})(A;;FA;;;${USER})`)).toBe(
`unexpected rule for ${builtinAdmin}`
)
})
})
@@ -1,105 +0,0 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import type * as NodeFs from 'node:fs'
import { tmpdir } from 'node:os'
import { delimiter, join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { resolveCliCommandAsync } from './node-cli-command-async-resolution'
import { resolveCliCommand } from './node-cli-command-resolution'
const syncFs = vi.hoisted(() => ({ forbidden: false, calls: new Array<string>() }))
// Throws from every sync read a CLI lookup could make while forbidden, proving the async lookup makes none.
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof NodeFs>()
const guard =
<A extends unknown[], R>(name: string, read: (...args: A) => R) =>
(...args: A): R => {
if (syncFs.forbidden) {
syncFs.calls.push(name)
throw new Error(`sync fs call: ${name}`)
}
return read(...args)
}
return {
...actual,
accessSync: guard('accessSync', actual.accessSync),
existsSync: guard('existsSync', actual.existsSync),
lstatSync: guard('lstatSync', actual.lstatSync),
readdirSync: guard('readdirSync', actual.readdirSync),
readFileSync: guard('readFileSync', actual.readFileSync),
realpathSync: guard('realpathSync', actual.realpathSync),
statSync: guard('statSync', actual.statSync)
}
})
let root: string
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'orca-cli-resolve-async-'))
})
afterEach(() => {
syncFs.forbidden = false
syncFs.calls = []
rmSync(root, { recursive: true, force: true })
})
function stage(...relative: string[]): void {
for (const path of relative) {
mkdirSync(join(root, path, '..'), { recursive: true })
writeFileSync(join(root, path), '')
}
}
// Windows' spawn recheck uses the async resolver; it must pick what panes' sync resolver picks.
// platform: 'win32' skips the X_OK check, so these run on any host.
describe('resolveCliCommandAsync agrees with resolveCliCommand on Windows', () => {
const options = (...dirs: string[]) => ({
pathEnv: dirs.map((dir) => join(root, dir)).join(delimiter),
homePath: join(root, 'home'),
platform: 'win32' as const
})
it.each([
{
name: 'the .cmd shim beats .exe and .bat in one dir',
files: ['a/codex.exe', 'a/codex.bat', 'a/codex.cmd'],
expected: 'a/codex.cmd'
},
{ name: '.exe beats .bat', files: ['a/codex.bat', 'a/codex.exe'], expected: 'a/codex.exe' },
{
name: 'an earlier PATH dir beats a better extension later',
files: ['a/codex.bat', 'b/codex.cmd'],
expected: 'a/codex.bat'
},
{
name: 'a PATH miss falls back to the npm global dir',
files: ['home/AppData/Roaming/npm/codex.cmd'],
expected: 'home/AppData/Roaming/npm/codex.cmd'
},
{
name: 'a PATH copy beats an install-dir copy',
files: ['home/AppData/Roaming/npm/codex.cmd', 'b/codex.exe'],
expected: 'b/codex.exe'
},
{
name: "nvm's default alias outranks a newer nvm install",
files: [
'home/.nvm/alias/default',
'home/.nvm/versions/node/v22.0.0/bin/codex.cmd',
'home/.nvm/versions/node/v20.1.0/bin/codex.cmd'
],
alias: '20',
expected: 'home/.nvm/versions/node/v20.1.0/bin/codex.cmd'
},
{ name: 'a miss everywhere returns the bare name', files: [], expected: null }
])('$name', async ({ files, alias, expected }) => {
stage(...files)
if (alias) {
writeFileSync(join(root, 'home/.nvm/alias/default'), alias)
}
const sync = resolveCliCommand('codex', options('a', 'b'))
expect(sync).toBe(expected === null ? 'codex' : join(root, expected))
expect(await resolveCliCommandAsync('codex', options('a', 'b'))).toBe(sync)
})
})
@@ -1,135 +0,0 @@
import { spawnSync } from 'node:child_process'
import {
chmodSync,
existsSync,
mkdirSync,
mkdtempSync,
rmSync,
statSync,
writeFileSync
} from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { getPosixClaudeShellFunction, getFishClaudeShellFunction } from './claude-shell-function'
import { agentSessionSignInCommand } from '../../../agent-session/lifecycle/launch/agent-session-setup-commands'
// Skip missing zsh/fish instead of failing with exit 127 on CI images.
const POSIX_SHELLS = ['/bin/bash', '/bin/zsh'].filter((shell) => existsSync(shell))
const FISH = ['/opt/homebrew/bin/fish', '/usr/local/bin/fish', '/usr/bin/fish'].find(existsSync)
const SHELLS = [...POSIX_SHELLS, ...(FISH ? [FISH] : [])]
const roots: string[] = []
afterEach(() => {
roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true }))
})
function fixture() {
const root = mkdtempSync(join(tmpdir(), 'claude-shell-'))
roots.push(root)
const a = join(root, 'account a ü')
const bin = join(root, 'bin')
for (const dir of [a, bin]) {
mkdirSync(dir)
}
const fake = join(bin, 'claude')
writeFileSync(
fake,
'#!/bin/sh\nprintf "HOME=%s KEY=%s TWIN=%s\\n" "${CLAUDE_CONFIG_DIR-default}" "${ANTHROPIC_API_KEY-none}" "${ORCA_CLAUDE_INJECTED_CONFIG_DIR-none}"\nexit 23\n'
)
chmodSync(fake, 0o700)
const pointer = join(root, 'selected')
const run = (
shell: string,
env: string[] = [],
fakeKind: 'summary' | 'direct' = 'summary',
userSetup = '',
command = 'claude'
) => {
if (fakeKind === 'direct') {
// A subshell left between the pane shell and Claude leads Claude's foreground group.
writeFileSync(fake, '#!/bin/sh\n[ "$PPID" = "$PANE_SHELL_PID" ] && echo direct\n')
}
const fish = shell.endsWith('fish')
const fn = fish ? getFishClaudeShellFunction() : getPosixClaudeShellFunction()
// Abort if system config shadows the fake with a real claude binary.
const guard = fish
? `test (command -s claude) = '${fake}'; or exit 97`
: `[ "$(command -v claude)" = '${fake}' ] || exit 97`
const result = spawnSync(
'/usr/bin/env',
[
'-i',
`HOME=${root}`,
`PATH=${bin}:/usr/bin:/bin`,
`ORCA_CLAUDE_PROFILE_POINTER=${pointer}`,
'ANTHROPIC_API_KEY=fake',
...env,
shell,
...(fish ? ['--no-config'] : shell.endsWith('zsh') ? ['-f'] : ['--norc', '--noprofile']),
'-c',
`${guard}\n${userSetup}\n${fn}\n${command}`
],
{ encoding: 'utf8', cwd: root }
)
expect(result.status).not.toBe(97)
expect(result.stderr).toBe('')
return result
}
return { a, pointer, run }
}
const injected = (home: string) => [
`CLAUDE_CONFIG_DIR=${home}`,
`ORCA_CLAUDE_INJECTED_CONFIG_DIR=${home}`
]
describe.each(SHELLS)('the claude function in %s', (shell) => {
it('signs the system account in while a managed profile is selected, preserving later routing', () => {
const f = fixture()
writeFileSync(f.pointer, f.a)
const command = agentSessionSignInCommand('claude', { account: 'system', remote: false })
const env = [...injected(f.a), 'ORCA_CLAUDE_USER_CONFIG_DIR=/user/system account/']
const result = f.run(shell, env, 'summary', '', `${command}; claude`)
expect(result.stdout).toBe(
`HOME=/user/system account/ KEY=fake TWIN=none\nHOME=${f.a} KEY=fake TWIN=${f.a}\n`
)
expect(result.status).toBe(23)
expect(f.run(shell, injected(f.a), 'summary', '', command!).stdout).toBe(
'HOME=default KEY=fake TWIN=none\n'
)
})
it('creates a missing account folder and runs Claude in it, printing nothing', () => {
const f = fixture()
const fresh = join(f.a, 'claude-profiles', 'id', 'home')
writeFileSync(f.pointer, fresh)
const result = f.run(shell)
expect(result.stdout).toBe(`HOME=${fresh} KEY=fake TWIN=${fresh}\n`)
expect(result.status).toBe(23)
expect(existsSync(fresh)).toBe(true)
// Match private login-folder permissions.
expect(statSync(fresh).mode & 0o777).toBe(0o700)
})
it.skipIf(!POSIX_SHELLS.includes(shell))(
'keeps the user’s own claude function when the cwd has a claude entry',
() => {
const f = fixture()
writeFileSync(f.pointer, f.a)
mkdirSync(join(f.a, '..', 'claude'))
const userFn = 'claude() { echo user function; }'
expect(f.run(shell, [], 'summary', userFn).stdout).toBe('user function\n')
}
)
it.skipIf(shell.endsWith('fish'))(
'replaces the subshell so Claude is a direct child of the pane shell',
() => {
const f = fixture()
const own = 'ORCA_CLAUDE_USER_CONFIG_DIR=/user/own'
const setup = 'export PANE_SHELL_PID=$$'
writeFileSync(f.pointer, f.a)
expect(f.run(shell, [], 'direct', setup).stdout).toBe('direct\n')
writeFileSync(f.pointer, '')
expect(f.run(shell, [...injected(f.a), own], 'direct', setup).stdout).toBe('direct\n')
expect(f.run(shell, [], 'direct', setup).stdout).toBe('direct\n')
}
)
})
@@ -1,89 +0,0 @@
/** Real-shell byte round trips validate one POSIX startup string across sh/bash/zsh/dash/fish.
* Regression cases retain fish backslashes/apostrophes and zsh builtin eval, which command eval cannot run. */
import { execFileSync } from 'node:child_process'
import { existsSync, mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterAll, describe, expect, it } from 'vitest'
import { resolveFishBinary } from '../testing/fish-binary-requirement'
import { clearEnvCommand } from '../../agent-launch/startup/tui-agent-startup-shell'
const FISH = resolveFishBinary(4)
type LiveShell = { name: string; path: string }
function discoverShells(): LiveShell[] {
const shells: LiveShell[] = []
for (const path of [
'/bin/sh',
'/bin/bash',
'/bin/zsh',
'/bin/dash',
'/usr/bin/dash',
'/bin/ksh'
]) {
if (existsSync(path) && !shells.some((shell) => shell.name === basename(path))) {
shells.push({ name: basename(path), path })
}
}
if (FISH.available) {
// Sandbox PATH cannot resolve bare fish.
const path = FISH.path.includes('/')
? FISH.path
: execFileSync('command', ['-v', FISH.path], { encoding: 'utf8', shell: true }).trim()
shells.push({ name: 'fish', path })
}
return shells
}
function basename(path: string): string {
return path.split('/').pop() ?? path
}
// Fish needs a writable HOME for universal variables or every launch warns.
const SANDBOX_HOME = mkdtempSync(path.join(tmpdir(), 'orca-shell-portability-'))
function sandboxEnv(): NodeJS.ProcessEnv {
return {
PATH: '/usr/bin:/bin:/usr/sbin:/sbin',
HOME: SANDBOX_HOME,
XDG_CONFIG_HOME: path.join(SANDBOX_HOME, 'config'),
XDG_DATA_HOME: path.join(SANDBOX_HOME, 'data')
}
}
function runInShell(shell: LiveShell, script: string): string {
return execFileSync(shell.path, ['-c', script], {
encoding: 'utf8',
timeout: 20_000,
env: sandboxEnv()
})
}
const SHELLS = discoverShells()
afterAll(() => {
rmSync(SANDBOX_HOME, { recursive: true, force: true })
})
// Windows has no discovered POSIX shells; skip instead of failing on missing tools.
describe.skipIf(process.platform === 'win32')(
'one POSIX startup dialect is correct in every Unix shell',
() => {
describe.each(SHELLS)('$name', (shell) => {
// Keep -g: erasing a lone universal would permanently change future fish sessions, including clipboard launches without injected env.
it.runIf(shell.name === 'fish')('never deletes a lone universal variable', () => {
const clear = clearEnvCommand('ORCA_PI_PREFILL', 'posix')
const probe = `set -Ux ORCA_PI_PREFILL persisted; ${clear}; set -q ORCA_PI_PREFILL; and echo "RESULT=$ORCA_PI_PREFILL"; or echo RESULT=DESTROYED; set -Ue ORCA_PI_PREFILL`
expect(runInShell(shell, probe)).toContain('RESULT=persisted')
})
// Erase the injected global so the user’s shadowed universal reappears.
it.runIf(shell.name === 'fish')('reveals a shadowed universal instead of deleting it', () => {
const clear = clearEnvCommand('ORCA_PI_PREFILL', 'posix')
const probe = `set -Ux ORCA_PI_PREFILL mine; set -gx ORCA_PI_PREFILL injected; ${clear}; echo "RESULT=$ORCA_PI_PREFILL"; set -Ue ORCA_PI_PREFILL`
expect(runInShell(shell, probe)).toContain('RESULT=mine')
})
})
}
)
@@ -1,233 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import {
getDiscardAllPaths,
getStageAllPaths,
getUnstageAllPaths,
isStageableStatusEntry,
runDiscardAllForArea
} from './source-control-discard-all-sequence'
import type { GitStatusEntry } from '../../git/status/git-status-types'
function entry(partial: Partial<GitStatusEntry> & { path: string }): GitStatusEntry {
return {
status: 'modified',
area: 'unstaged',
...partial
}
}
describe('getDiscardAllPaths', () => {
it('skips non-recursing present submodules and children but keeps restorable ones', () => {
const submodule = { commitChanged: false, trackedChanges: true, untrackedChanges: false }
const entries: GitStatusEntry[] = [
entry({ path: 'dirty-sub', submodule }),
entry({ path: 'dirty-sub/file.ts', submoduleRoot: 'dirty-sub' }),
entry({ path: 'deleted-sub', status: 'deleted', submodule }),
entry({ path: 'recursing-sub', submodule: { ...submodule, restoreRecurses: true } }),
entry({ path: 'parent.ts' })
]
expect(getDiscardAllPaths(entries, 'unstaged')).toEqual([
'deleted-sub',
'recursing-sub',
'parent.ts'
])
})
it('skips entries with an unresolved conflict', () => {
const entries: GitStatusEntry[] = [
entry({ path: 'clean.ts', area: 'unstaged' }),
entry({
path: 'conflict.ts',
area: 'unstaged',
conflictKind: 'both_modified',
conflictStatus: 'unresolved'
})
]
// Restoring unresolved conflicts silently clears the u record before review, matching the per-row discard guard.
expect(getDiscardAllPaths(entries, 'unstaged')).toEqual(['clean.ts'])
})
it('skips entries resolved locally but not yet re-staged', () => {
const entries: GitStatusEntry[] = [
entry({ path: 'clean.ts', area: 'unstaged' }),
entry({
path: 'resolved.ts',
area: 'unstaged',
conflictKind: 'both_modified',
conflictStatus: 'resolved_locally'
})
]
// Bulk discard must preserve local resolutions or users would have to resolve them again.
expect(getDiscardAllPaths(entries, 'unstaged')).toEqual(['clean.ts'])
})
})
describe('getStageAllPaths', () => {
it('skips entries with an unresolved conflict', () => {
const entries: GitStatusEntry[] = [
entry({ path: 'clean.ts', area: 'unstaged' }),
entry({
path: 'conflict.ts',
area: 'unstaged',
conflictKind: 'both_modified',
conflictStatus: 'unresolved'
})
]
// git add silently clears unresolved u records before review, matching the per-row Stage guard.
expect(getStageAllPaths(entries, 'unstaged')).toEqual(['clean.ts'])
})
it('includes entries that are resolved locally', () => {
const entries: GitStatusEntry[] = [
entry({ path: 'clean.ts', area: 'unstaged' }),
entry({
path: 'resolved.ts',
area: 'unstaged',
conflictKind: 'both_modified',
conflictStatus: 'resolved_locally'
})
]
// Staging a local resolution finishes the normal conflict workflow and must remain available.
expect(getStageAllPaths(entries, 'unstaged')).toEqual(['clean.ts', 'resolved.ts'])
})
it('skips submodule rows that only contain nested worktree dirtiness', () => {
const entries: GitStatusEntry[] = [
entry({
path: 'nested-repo',
area: 'unstaged',
submodule: { commitChanged: false, trackedChanges: false, untrackedChanges: true }
}),
entry({
path: 'changed-gitlink',
area: 'unstaged',
submodule: { commitChanged: true, trackedChanges: false, untrackedChanges: true }
})
]
expect(getStageAllPaths(entries, 'unstaged')).toEqual(['changed-gitlink'])
})
})
describe('status entry stageability', () => {
it('marks lazily-expanded submodule-internal entries as not stageable', () => {
const innerEntry = entry({
path: 'flutter_mine/lib/main.dart',
area: 'unstaged',
submoduleRoot: 'flutter_mine'
})
// Parent-worktree git add cannot stage inner submodule changes.
expect(isStageableStatusEntry(innerEntry)).toBe(false)
expect(getStageAllPaths([innerEntry], 'unstaged')).toEqual([])
})
})
describe('getUnstageAllPaths', () => {
it('includes staged conflict rows', () => {
const entries: GitStatusEntry[] = [
entry({ path: 'clean.ts', area: 'staged' }),
entry({
path: 'conflict.ts',
area: 'staged',
conflictKind: 'both_modified',
conflictStatus: 'unresolved'
}),
entry({
path: 'resolved.ts',
area: 'staged',
conflictKind: 'both_modified',
conflictStatus: 'resolved_locally'
})
]
// Unstaging conflicts safely mirrors the per-row action; no conflict filtering is needed.
expect(getUnstageAllPaths(entries)).toEqual(['clean.ts', 'conflict.ts', 'resolved.ts'])
})
})
describe('runDiscardAllForArea', () => {
function makeDeps(
overrides: {
bulkUnstageError?: unknown
discardManyError?: unknown
discardOneError?: (path: string) => unknown
} = {}
) {
const bulkUnstageCalls: string[][] = []
const discardManyCalls: string[][] = []
const discardOneCalls: string[] = []
const errors: unknown[] = []
const bulkUnstage = vi.fn(async (paths: string[]) => {
bulkUnstageCalls.push([...paths])
if (overrides.bulkUnstageError !== undefined) {
throw overrides.bulkUnstageError
}
})
const discardMany = vi.fn(async (paths: string[]) => {
discardManyCalls.push([...paths])
if (overrides.discardManyError !== undefined) {
throw overrides.discardManyError
}
})
const discardOne = vi.fn(async (path: string) => {
discardOneCalls.push(path)
if (overrides.discardOneError) {
const err = overrides.discardOneError(path)
if (err !== undefined) {
throw err
}
}
})
const onError = vi.fn((error: unknown) => {
errors.push(error)
})
return {
deps: { bulkUnstage, discardOne, onError },
depsWithBulkDiscard: { bulkUnstage, discardMany, discardOne, onError },
bulkUnstageCalls,
discardManyCalls,
discardOneCalls,
errors,
bulkUnstage,
discardMany,
discardOne,
onError
}
}
it('falls back to per-file discard when bulk discard rejects', async () => {
const ctx = makeDeps({ discardManyError: new Error('unknown method') })
const result = await runDiscardAllForArea('unstaged', ['a.ts', 'b.ts'], ctx.depsWithBulkDiscard)
expect(result).toEqual({ discarded: ['a.ts', 'b.ts'], failed: [], aborted: false })
expect(ctx.discardManyCalls).toEqual([['a.ts', 'b.ts']])
expect(ctx.discardOneCalls).toEqual(['a.ts', 'b.ts'])
expect(ctx.onError).not.toHaveBeenCalled()
})
it('aborts and skips the discard loop if bulk-unstage rejects', async () => {
const error = new Error('index locked')
const ctx = makeDeps({ bulkUnstageError: error })
const result = await runDiscardAllForArea('staged', ['a.ts', 'b.ts'], ctx.deps)
expect(result).toEqual({ discarded: [], failed: [], aborted: true })
// Abort after failed unstage; restoring only the worktree would leave a mismatched staged delta.
expect(ctx.discardOne).not.toHaveBeenCalled()
expect(ctx.errors).toEqual([error])
})
it('continues past a per-file discard failure and records it in `failed`', async () => {
const error = new Error('EPERM')
const ctx = makeDeps({
discardOneError: (path) => (path === 'b.ts' ? error : undefined)
})
const result = await runDiscardAllForArea('unstaged', ['a.ts', 'b.ts', 'c.ts'], ctx.deps)
expect(result).toEqual({
discarded: ['a.ts', 'c.ts'],
failed: ['b.ts'],
aborted: false
})
expect(ctx.discardOneCalls).toEqual(['a.ts', 'b.ts', 'c.ts'])
// Reserve aborted for failed bulk unstage so callers can distinguish no work from partial success.
expect(ctx.errors).toEqual([error])
})
})
@@ -1,82 +0,0 @@
import { describe, expect, it } from 'vitest'
import { createDictationDictionary } from './dictation-term-spelling'
const spell = (terms: Parameters<typeof createDictationDictionary>[0], text: string): string =>
createDictationDictionary(terms)!(text)
describe('createDictationDictionary', () => {
// Parakeet v3's real output for the dev bench's code-term clips.
it('joins the words a model splits a code term into back into the term', () => {
const terms = [
{ term: 'useAudioCapture' },
{ term: 'usePcmWorklet' },
{ term: 'stt-worker.ts' },
{ term: 'numThreads' },
{ term: 'useMemo' },
{ term: 'onChange' }
]
expect(
spell(terms, 'Rename use audio capture to use PCM worklet in the dictation controller.')
).toBe('Rename useAudioCapture to usePcmWorklet in the dictation controller.')
expect(spell(terms, 'Open stt worker TS and set num threads to 4.')).toBe(
'Open stt-worker.ts and set numThreads to 4.'
)
expect(spell(terms, 'Wrap it in use memo and pass the on-change call back.')).toBe(
'Wrap it in useMemo and pass the onChange call back.'
)
})
// Parakeet v3 and Whisper large-v3 turbo's real output for `say` clips of the terms.
it('spells a misheard word as the term when it sounds the same and is spelled close', async () => {
const clean = createDictationDictionary([
{ term: 'Supabase' },
{ term: 'Vercel' },
{ term: 'oxlint' },
{ term: 'Silero' }
])!
await expect
.poll(() => clean('We moved the auth tables from Superbase to Postgres last week.'), {
timeout: 5000
})
.toBe('We moved the auth tables from Supabase to Postgres last week.')
expect(clean('Deploy the preview to Versal before the review.')).toBe(
'Deploy the preview to Vercel before the review.'
)
expect(clean('Run auxlint on the changed files before you push.')).toBe(
'Run oxlint on the changed files before you push.'
)
expect(clean('Parakeet and Celero both run inside the speech child.')).toBe(
'Parakeet and Silero both run inside the speech child.'
)
expect(clean("It doesn't work on Versal.")).toBe("It doesn't work on Vercel.")
})
it('leaves ordinary words, names, runs of words and other languages alone', async () => {
const clean = createDictationDictionary([
{ term: 'Bazel' },
{ term: 'Jupyter' },
{ term: 'Istio' },
{ term: 'Saleor' },
{ term: 'Vercel' }
])!
await expect
.poll(() => clean('Deploy the preview to Versal before the review.'), { timeout: 5000 })
.toBe('Deploy the preview to Vercel before the review.')
for (const text of [
'The vessel reached the harbor just after noon.',
'The phone has a thin bezel.',
'The planet Jupiter is bright tonight.',
'It is too late to call him now.',
'The ship was a very fast sailer.',
'Despliega la vista previa en Versal antes de la revisión.'
]) {
expect(clean(text)).toBe(text)
}
// A bilingual model's Chinese sentence is not English, even though English is one of its languages.
const bilingual = createDictationDictionary([{ term: 'Vercel' }], ['zh', 'en'])!
expect(bilingual('请在 Versal 上部署预览。')).toBe('请在 Versal 上部署预览。')
expect(bilingual('Deploy the preview to Versal before the review.')).toBe(
'Deploy the preview to Vercel before the review.'
)
})
})
@@ -1,124 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { WorkspaceAttachment } from '../worktree/types'
import { getWorkspaceAttachmentKey } from './workspace-attachment-normalization'
import {
summarizeWorkspaceReviewChecks,
type WorkspaceReviewCheckDetails
} from './workspace-review-checks'
function attachment(number: number, provider: 'github' | 'gitlab' = 'github'): WorkspaceAttachment {
return {
provider,
type: provider === 'gitlab' ? 'mr' : 'pr',
number,
url:
provider === 'github'
? `https://github.com/acme/orca/pull/${number}`
: `https://gitlab.com/acme/orca/-/merge_requests/${number}`
}
}
function details(
item: WorkspaceAttachment,
status: 'success' | 'failure' | 'pending' | 'neutral',
stale = false
): WorkspaceReviewCheckDetails {
return { stale, review: { provider: item.provider, number: item.number, url: item.url, status } }
}
function map(
entries: [WorkspaceAttachment, WorkspaceReviewCheckDetails][]
): Record<string, WorkspaceReviewCheckDetails> {
return Object.fromEntries(
entries.map(([item, detail]) => [getWorkspaceAttachmentKey(item), detail])
)
}
describe('all workspace review checks', () => {
it('retains matched lifecycle and staleness without check results and rejects foreign details', () => {
const item = attachment(1)
const retained = {
stale: true,
review: { provider: 'github', number: 1, url: item.url, state: 'merged' }
} as const
expect(summarizeWorkspaceReviewChecks([item], map([[item, retained]]))).toMatchObject({
reviewState: 'merged',
stale: 1,
state: 'unknown',
unknown: 1
})
const foreign = {
...retained,
review: { ...retained.review, url: 'https://github.com/other/project/pull/1' }
}
expect(summarizeWorkspaceReviewChecks([item], map([[item, foreign]]))).toMatchObject({
reviewState: undefined,
stale: 0,
state: 'unknown'
})
})
it('aggregates every review rather than a selected compatibility slot', () => {
const first = attachment(1)
const second = attachment(2)
expect(
summarizeWorkspaceReviewChecks(
[first, second],
map([
[first, details(first, 'success')],
[second, details(second, 'failure')]
])
)
).toMatchObject({ state: 'failure', total: 2, known: 2, passed: 1, failed: 1 })
})
it('keeps all unknown or partially known collections from looking green', () => {
const first = attachment(1)
const second = attachment(2)
expect(summarizeWorkspaceReviewChecks([first, second], {})).toMatchObject({
state: 'unknown',
unknown: 2
})
expect(
summarizeWorkspaceReviewChecks([first, second], map([[first, details(first, 'success')]]))
).toMatchObject({ state: 'unknown', known: 1, unknown: 1 })
})
it('never certifies stale success and conservatively retains stale failure', () => {
const item = attachment(1)
expect(
summarizeWorkspaceReviewChecks([item], map([[item, details(item, 'success', true)]]))
).toMatchObject({ state: 'unknown', stale: 1 })
expect(
summarizeWorkspaceReviewChecks([item], map([[item, details(item, 'failure', true)]]))
).toMatchObject({ state: 'failure', stale: 1 })
})
it('isolates equal numbers by provider and repository scope', () => {
const github = attachment(1)
const gitlab = attachment(1, 'gitlab')
const foreign = { ...github, url: 'https://github.com/other/project/pull/1' }
expect(
summarizeWorkspaceReviewChecks(
[github, gitlab],
map([
[github, details(gitlab, 'success')],
[gitlab, details(github, 'failure')]
])
)
).toMatchObject({ state: 'unknown', unknown: 2, failed: 0 })
expect(
summarizeWorkspaceReviewChecks([github], map([[github, details(foreign, 'success')]]))
).toMatchObject({ state: 'unknown', unknown: 1 })
})
it('ignores tasks and deduplicates review metadata without filtering lifecycle states', () => {
const first = attachment(1)
const second = attachment(2)
const task: WorkspaceAttachment = { provider: 'github', type: 'issue', number: 3 }
expect(
summarizeWorkspaceReviewChecks(
[first, first, second, task],
map([
[first, details(first, 'failure')],
[second, details(second, 'success')]
])
)
).toMatchObject({ total: 2, failed: 1, state: 'failure' })
expect(summarizeWorkspaceReviewChecks([task], {})).toMatchObject({ state: 'none', total: 0 })
})
})